How do I manage Java timer tasks? - java

I'm looking for some guidance on how to manage multiple timer tasks. I'd like to be able to dynamically create timers and then when each timer is finished, it'll reset itself.
Example:
Timer 1
- perform action x
- reset to perform action x again in 30 minutes
Timer 2
- perform action y
- reset to perfom action y again in 10 minutes

What you want is the ScheduledExecutorService.
It allows you to schedule tasks to run at a given time or at a given rate.

The following code creates a timer and executes it every 1000 ms after an initial delay of 500 ms. You can easily define two or more timers this way.
TimerTask task = new TimerTask() {
#Override
public void run() {
System.out.println( "exec" );
}
};
new Timer().scheduleAtFixedRate( task, 500, 1000 );

Perhaps it could be worth reviewing Quartz Enterprise Job Scheduler
Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components or EJBs.

Related

What is the difference between Timer and Runnable?

I would like to know what exactly the difference is between these two classes, and when should I use each.
I am asking this because I am wondering about this sample code:
mStatusChecker = new Runnable() {
#Override
public void run() {
invalidate();
mHandler.postDelayed(mStatuschecker, (long) increment * 1000);
}
};
If I put the mHandler.postDelayed line of code before invalidate(), the Runnable is executed at almost double the speed. I am wondering if a Timer could be used instead to fix this problem.
Timer is a facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
It's better to user Timer functionality if you need timer functionality like task needing to be run at regular intervals.
Java java.util.Timer is a utility class that can be used to schedule a
thread to be executed at certain time in future. Java Timer class can
be used to schedule a task to be run one-time or to be run at regular
intervals. Java Timer class is thread safe and multiple threads can
share a single Timer object without need for external synchronization.
https://www.journaldev.com/1050/java-timer-timertask-example
Timer is not an Android class, it's a Java SDK class included in the Android SDK for compatibility with legacy code. It does not play well with the Android component lifecycle and requires extra code to interact with the UI. In short, do not use Timer on Android.

multiple schedule calls with single timer

I am reading about timers in Java SDK 1.3
It is mentioned as follows in POSA volume 2 in active object pattern
JDK 1.3 introduced a mechansim for executing timer-based tasks
concurrently in the classes java.util.Timer and java.util.TimerTask.
When ever the scheduled execution time of a task occurs it is
executed. The scheduling calls are executed in the clinets thread,
while the tasks themselves are executed in a thread owned by Timer
object. A timer internal task queue is protected by locks because the
two threads outlined above operate on it concurrently.
The task queue is implemented as a priority queue so that the next
TimerTask to expire can be identified efficiently. The timer thread
simply waits until this expiration.
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.format("Time's up!%n");
timer.cancel(); //Terminate the timer thread
}
}
public static void main(String args[]) {
new Reminder(5);
System.out.format("Task scheduled.%n");
}
}
My question is
Can we have multiple schedule functions with single timer? Request to give an example here and how it works. For example if we have two scheduled one task for every 5 seconds as shown above and another for every 12 seconds but I want to use same Reminder object instead of using another (i.e., creating) Reminder object. I want to know how internally it works like how timer stated like 5,5,2, 3, and so on . (as I have same kind of requirement in my project which I have to do in C++ with out using boost. I am planning to use single timer rather than multiple timers.
What is delay argument here and how it is used.
schedule(TimerTask task, long delay, long period)
Thanks for your time and help.
If you don't have to use SDK 1.3, you can use Java 5.0 which introduced the ScheduledExecutorService which makes Timers redundant IMHO.
The ScheduledExecutorService has been around more than 9 years, perhaps it is time to upgrade.
BTW 1.3 was end of lifed, before Sun officially had End of Life dates. It is ancient and unless you like history lessons, I suggest you live in the present. ;)
BTW Java 5.0 and Java 6 are both end of life and Java 7 will have its end of life date announced next year.
So I would look at Java 7 or 8 if I were you, and ignore anything which is more than a few years old because there are many practices which are either bad, or out dated on the Internet and they don't get updated.
If you like learning about bad or out of date practices, the rose india web site is the finest collection I have found. ;)

Force regular execution of periodic task within Java application

ScheduledExecutorService seems to have the problem that if it can't get a free thread the periodic task will happen with delay. Unfortunately for me, the periodic task it's assigned to really does need to happen fairly on schedule. At present it's scheduled for once per minute but sometimes due to the application being busy with other things (I assume this is why) it fails to make it within five minutes, and five minutes happens to be the "major production bugs" threshold.
How to force this via prioritizing or otherwise controlling the thread balancer?
If your ScheduledExecutorService is used for other tasks or if your task sometimes takes more than 1 minute to run, you can simply increase the number of threads available in your ScheduledExecutorService. So if one task has not finished running, the executor will still be able to run a new one.
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
(I picked 10 randomly - if you run your task every minute and it can run for up to 5 minutes, that leaves you some margin for error)

Looking for a scalable "at" implementation

I'm looking for a scalable "at" replacement, with high availability. It must support adding and removing jobs at runtime.
Some background:
I have an application where I trigger millions of events, each event occurs just once. I don't need cron like mechanisms (first Sunday of the month, etc), simply date, time and context.
Currently I'm using the Quartz scheduler, and while it is a very good project, it has difficulties to handle the amount of events we throw at it, even after a lot of tweaking (sharding, increasing polling interval, etc.) due to the basic locking it performs on the underline database. Also, it is a bit overkill for us, as basically we have millions of one time triggers, and relatively small number of jobs.
I'd appreciate any suggestion
If I was facing the same scenario I would do the following...
Setup a JMS queue cluster (e.g RabbitMQ or ActiveMQ) using a queue replication setup over a few boxes.
Fire all the events at my nice highly-available JMS queue.
Then I would code an agent application that popped the events of the JMS queue as needed, I could run multiple agents on multiple boxes and have that combined with the correct JMS failover url etc.
You could also use the same sort of model if your jobs are firing the events...
Fyi, a nicer way of scheduling in core Java is as follows:
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(sensibleThreadCount);
threadPool.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
//Pop events from event queue.
//Do some stuff with them.
}
}, initialDelay, period, TimeUnit.X);
Maybe just use JGroups shared tree with tasks sorted by execution time. Nodes will will take first task and schedule timer, which will execute at given time. On task remove timer can be canceled.
So basically you can use just JGroups and simple java Timers/Executors.
I didn't read it whole, but here is some proof of concept or maybe even solution
how about the java timer?
import java.util.*;
public class MyTask extends TimerTask{
public void run(){
System.out.println( "do it!" );
}
}
and then
Timer timer = new Timer();
MyTask job1 = new MyTask();
// once after 2 seconds
timer.schedule( job1, 2000 );
job1.cancel();
MyTask job2 = new MyTask();
// nach each 5 seconds after 1 second
timer.schedule ( job2, 1000, 5000 );

Scheduling multiple tasks using timers

How can I schedule multiple tasks using java.util.Timer. I want to read multiple files using timers. I think I have to give each file a different TimerTask so that one file gets one instance of TimerTask and other file gets another, but I don't know how to do it. Please help. Thanks in advance. Here is what I'm doing:
Timer timer = new Timer();
// repeat the check every second
timer.schedule(fileWatcherTask, new Date(), 1000);
As javadoc of Timer class indicates your tasks should take very few time. In this case you can forget about time clash. If your tasks take more then 0.1 seconds run them in separate thread. I mean use Timer as a trigger that just makes task to start in separate thread.
you can also use quartz scheduler for that refer http://www.mkyong.com/java/quartz-scheduler-example/
if you want to use timer class see the example in following image
refer link for more details

Categories