Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to program a timer that keeps track of multiple events in Java?

I work at a place where students take tests in rooms. Each student's exit time is noted on a board, and I must remember to get them when their time is up.

So I would like to write a Java program that allows me to input an exit time and then keep track of the current time until that it reaches that future exit time.

My problem:

  1. What would be the best type of data to use for such a task? As of now I'm looking at both date and calendar. Worst comes to worst though, I'll figure out some way to get a raw input time like "2:43 PM" and convert it to milliseconds and measure it in accordance to the current time method Java system has.

  2. I want to be able to input multiple student entries and have them all be timed at the same time. How would I do that? Because the way I figure it, you need a loop that keeps the program running, but at the same time makes sure that currentTime < any of the exit times. What would be the best way of doing that? As of now I'm thinking of having an array of exit times and just systematically comparing each element to current time in some kind of loop, and when one exit is reached, it's removed from the array and a message is displayed.

And this loop would run every minute because I'll have some kind of wait function to prevent taking up resources on constant comparisons.

Any advice would be appreciated.

like image 688
Dev Avatar asked Nov 29 '25 23:11

Dev


2 Answers

Java.util.Timer and TimerTask come to mind to avoid recreating existing functionality.

like image 54
madth3 Avatar answered Dec 01 '25 13:12

madth3


The easiest thing would be to keep a list of students, each with a name and exit time.

Every "tick" of the clock, check to see if the current time is >= each student's exit time.

If so, print out the name(s) of "expired" students, and either remove them from the list, or mark them as "expired" so they're no longer checked.

You'd want to have that list be synchronized so you wouldn't add a student during the iteration, but the event loop will happen very quickly, so this shouldn't be a serious issue at all.

I agree with @madth3; just use existing mechanisms for something this simple.

like image 34
Dave Newton Avatar answered Dec 01 '25 13:12

Dave Newton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!