Java time based execution - java

I want to do the following. I count the occurence of an event in my program. What I wish to achieve is that at the end of every hour (Of the MST i.e the time zone where I am in) the count be recorded in the database for that hour. All I need is a code snippet which would execute at the end of every hour. Note that I don't want the thread to sleep because I also need to update counts when events occur.

You can implement a TimerTask so search for that. Or if you can use Quartz. Google search should be your first stop.

In Java, there's no way to ensure that a Runnable gets executed exactly at a given time.
You can only schedule a Runnable to be executed at intervals of approximately a given time. If that's enough for you, then a java.util.Timer or Executors.newSingleThreadScheduledExecutor() is good enough. You only need to put your counter in a thread-safe and atomic variable (AtomicInteger may be enough, depending on the numbers you are expecting to have).
If you want to have extreme precision, then you'd better modify your event handler, so that, before recording the event, it checks in which hour it is and, depending on that, it uses a different "slot" inside a queue. Finally, your scheduled task would gather old queue slots, removing them from the queue and storing to database. (I think this is excessive, but it's up to you).

Related

Multiple threads to run for a period of time

In an application, I'm sending a set of data to a class A which should actually sleep for a certain period of time and send the data back. There are multiple classes that use class A. So, there are multiple threads for each set of data.
Say for example, data A needs to sleep for time 10 seconds and then return. At the same time, there can be data B with time 20 seconds that it needs to wait before returning. So, time values is linked to data. What is the best possible way to do this?
My application uses Swing. Can I use Swing Timers/Swing Workers for this? (I might have to do a little data check before returning). Or should I use normal threads to run this and how?

Check if a time with matching units has past since the last check

I have a system that needs to trigger at certain intervals
If it is given the following:
minutes:25, seconds:10
It should then trigger every hour, 25 minutes and 10 seconds past the hour. For example, 7:25:10, 8:25:10, 9:25:10, and so on.
This would be simple enough, and I already have that code working. The problem is that it only works if the system checks at least once a second, otherwise it will miss a trigger.
So how can I check if the trigger units would have matched the current time units since the last check? The time between checks will vary greatly.
The trigger units are stored like this:
// units that must match the current time <Calendar Unit, Trigger>
private Map<Integer, Integer> triggerUnits;
First move to enum instead of map. The enum can contain hour, second, day, whatever. The good new is that such enum already exists in JDK and is called TimeUnit. Each member of this enum knows to translate the time to other units.
So, parse string hour:5. Translate the 5 hours to 3600*5*1000 milliseconds. This value will be used in your system. You have several possibilities but I'd suggest you to start from java.util.Timer. Each task can be scheduled in the timer. It uses one single thread for execution of all tasks.
If you want you can use use Executors framework:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(...);
The schedule method here directly works with time units. You even do not have to translate from one unit to another.
Each time you trigger the system, store the next time that the code needs to be triggered. During the checks, simply check if the current time has passed this "next time", and if so, then trigger the system.
Not precisely an answer for what you've asked, but I'd suggest using cron4j: the Predictor sounds like it is almost exactly what you need. Translate your spec into cron format, and then pass it to the Predictor and it will actually tell you the absolute time of the next execution. You can just schedule your check to happen at that moment in time or use a ScheduledExecutor to fire the job.
Might be a bit more complicated in some ways (and its an additional dependency), but completely eliminates the timing risk.

how to serialize multi-threaded program

I have many threads performing different operations on object and when nearly 50% of the task finished then I want to serialize everything(might be I want to shut down my machine ).
When I come back then I want to start from the point where I had left.
How can we achieve?
This is like saving state of objects of any game while playing.
Normally we save the state of the object and retrieve back. But here we are storing its process's count/state.
For example:
I am having a thread which is creating salary excel sheet for 50 thousand employee.
Other thread is creating appraisal letters for same 50 thousand employee.
Another thread is writing "Happy New Year" e-mail to 50 thousand employee.
so imagine multiple operations.
Now I want to shut down in between 50% of task finishes. say 25-30 thousand employee salary excel-sheet have been written and appraisal letters done for 25-30 thousand and so on.
When I will come back next day then I want to start the process from where I had left.
This is like resume.
I'm not sure if this might help, but you can achieve this if the threads communicate via in-memory queues.
To serialize the whole application, what you need to do is to disable the consumption of the queues, and when all the threads are idle you'll reach a "safe-point" where you can serialize the whole state. You'll need to keep track of all the threads you spawn, to know if they are in are idle.
You might be able to do this with another technology (maybe a java agent?) that freezes the JVM and allows you to dump the whole state, but I don't know if this exists.
well its not much different than saving state of object.
just maintain separate queues for different kind of inputs. and on every launch (1st launch or relaunch) check those queues, if not empty resume your 'stopped process' by starting new process but with remaining data.
say for ex. an app is sending messages, and u quit the app with 10 msg remaining. Have a global queue, which the app's senderMethod will check on every launch. so in this case it will have 10msg in pending queue, so it will continue sending remaining msgs.
Edit:
basically, for all resumable process' say pr1, pr2....prN, maintain queue of inputs, say q1, q2..... qN. queue should remove processed elements, to contain only pending inputs. as soon as u suspend system. store these queues, and on relaunching restore them. have a common routine say resumeOperation, which will call all resumable process (pr1, pr2....prN). So it will trigger the execution of methods with non-0 queues. which in tern replicate resuming behavior.
Java provides the java.io.Serializable interface to indicate serialization support in classes.
You don't provide much information about the task, so it's difficult to give an answer.
One way to think about a task is in terms of a general algorithm which can split in several steps. Each of these steps in turn are tasks themselves, so you should see a pattern here.
By cutting down each algorithms in small pieces until you cannot divide further you get a pretty good idea of where your task can be interrupted and recovered later.
The result of a task can be:
a success: the task returns a value of the expected type
a failure: somehow, something didn't turn right while doing computation
an interrupted computation: the work wasn't finished, but it may be resumed later, and the return value is the state of the task
(Note that the later case could be considered a subcase of a failure, it's up to you to organize your protocol as you see fit).
Depending on how you generate the interruption event (will it be a message passed from the main thread to the worker threads? Will it be an exception?), that event will have to bubble within the task tree, and trigger each task to evaluate if its work can be resumed or not, and then provide a serialized version of itself to the larger task containing it.
I don't think serialization is the correct approach to this problem. What you want is persistent queues, which you remove an item from when you've processed it. Every time you start the program you just start processing the queue from the beginning. There are numerous ways of implementing a persistent queue, but a database comes to mind given the scale of your operations.

java threading issue, right approach?

I am creating a java service which will continuously run in the background and the job of the service is to create a copy of the table at a particular date. To be exact, i read data from some table and if record_date in table matches the current date, i need to create the table copy. Then the service should sleep until the next date to run. Next date to run is also determined by looking at the record in the table.
Currently, how i do this, is to create a thread which runs in while(true) loop. and when thread is finished performing the task i.e. creating a table copy, I put it to sleep using Thread.sleep() until next time it needs to run. The number of milliseconds for thread to sleep, i calculate by taking the difference between the current date (date on which the task is performed by thread) and the next run date.
Is this the right approach, is using thread.sleep() for this particular scenario the right thing? I say this because next run date for a thread could be after three months or even a year. Also please let me know if i am not very clear here.
What about dissecting both operations?
Write a Java Job which when invokes checks for date in the table and create a copy.
Schedule the java job to run the way you want it to run.
Since we UNIX so cron helps us a lot in doing such tasks.
Have a look at the Lock interface. This is an abstraction for wait() and notify(), which is what you should use instead of sleep().
There is an answer here which illustrates why.
Check out the Java Timer API or the Quartz library

Alarm clock in Java

I want to make a program that will make a pop-up appear at a certain time in the future, eg. 5:00 tonight. Basically, the program is a reminder/notification system for appointments, meetings, etc.
My first instinct was to create a sort of "Clock Listener" that would check the computer's time every minute or so and see if currentTime == alarmTime. However, I don't know if this takes up too much resources or if it is just a bad practice to have your program constantly doing things like that. Also, for the alarm to be accurate, I think it would need to check every second, rather than every minute (since if it isn't checking the seconds and will go off at 5:00:xx, it could go off at 5:00:59, which may be too late for some people's liking). Is checking the clock every second too much?
My second thought was when the program starts running, calculate how long it is until the alarm is set to go off (say, in five hours). Then, wait five hours, and then sound the alarm. But then I thought, though unlikely, it would be possible for the user to change the computer's time, and then the alarm would go off at the wrong time. So this doesn't really work.
I've seen some solutions that use threads, but I'm not familiar with those yet, so I'd rather not use them.
I'm leaning towards the first solution, but I want to make sure it's efficient and won't slow down other programs. Perhaps I'm overthinking it and checking the clock is a trivial operation, but I just wanted to make sure I'm not doing anything wrong.
The sleep solution is very straightforward, but using java.util.Timer is not much harder, and gives you a clear way to extend your utility for multiple alarms, etc. Assuming you are going to use Swing to display the notification, note that your TimerTask will need to perform some of its work on the Swing event thread. SwingUtilities.invokeAndWait(...) will help you with that.
The first solution is OK. Waking up, checking the time, and going back to sleep should not be a problem at all. You can check every second if you want, but if you only need 1-minute resolution perhaps it is enough to check e.g. every 30 seconds.
The second approach has the problem you have outlined already. If you just go to sleep for the time remaining, and the user changes the time (or the time is changed by some other means, e.g. synchronisation with a time server), the alarm would go off at the wrong time. You could avoid this if you could register some sort of hook so that your program is called back when the system time changes, but you cannot easily do this in Java.

Categories