multiple schedule calls with single timer - java

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. ;)

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.

How to use TaskExecutorService discarding overlapping task in java

I have a scenario of running 2 separate standalone java polling tool where it would run some specific task with a fixed interval of 5 minutes.
MY scenario is (for each polling service):
1) if a task T0 is required more than 5 minutes to run and meanwhile after 5 minutes T5 comes and tries to execute , i would discard it, not wait,or relaunch (Discard overlapping tasks)
2) The next task would start at T10 normally.
My question is is using Quartz will be an overkill ? I f I use TaskExecutorService how can I check on time X that once task started on time X-5 is already running and I should discard it.
Note:
1) I must use JDK <= 6.0
2) I am not using under any framework like spring.
3) its an desktop tool so I need to launch it and it would run..
Any code snippet or direction is appreciated.
UPDATED for the answer of the comment below:
Yes its between tasks running in a single tool. The tools are different, there is no connection between the tools,they will run separately and has no relation.
a single tool runs a same task in a 5 minutes interval (like every file minute it looks inside a directory for files and if found parses those files and works with them).
If ,say for an example once the task is currently running started from first minute (it may take any amount of time), after 5 minutes the tool launches that task again looking for new files, but this time it will not parse/work with it, as a previous task is already running processing some files.so the new task will not execute and the system will dump it(NO queue/ no waiting / no sequential jobs ).
Another new task will again run on 5x time and if no other is running it will parse and process those files.
After seeing the reply on the question in the comment, you can use Excecutors to obtain a ScheduledExecutorService. Then, you can use the method scheduleWithFixedDelay to submit your task. This method reruns the task with a delay between the runs. The good thing for your case is that the delay counting starts after the current run finishes. This will give you what you want without using a boolean variable or a ReentrantLock as you will not have two tasks running at the same time. You just need to be careful to catch exceptions as an exception will cause subsequent runs of the task to be cancelled.
So lets assume you have a class MyTask which implements runnable
public class MyTask implements Runnable{
public void run() {
try {
//your task code here
} catch (...) {
//deal with the exceptions here
}
}
}
assuming you will run from main method, you can now use the class to schedule the reoccurring task:
public class TaskRunner{
private static final ScheduledExecutorService taskScheduler = Executors.newScheduledThreadPool(1);
public static void main(String[] args) {
taskScheduler.scheduleWithFixedDelay(new MyTask(),0,5,TimeUnit.MINUTES);
}
}
The solution is simple: use ScheduledThreadPoolExecutor.scheduleAtFixedRate(task, 5, min). Declare a common boolean variable isRunning=false. Each task checks this variable at the start, and if it is set already, exits, otherwise sets it to true and runs. At the end, sets it to false. Checking and setting should be done in a synchronized block.

How to call a thread to run on specific time in java?

I want o make threads execute at specific exact times (for example at: 2012-07-11 13:12:24 and 2012-07-11 15:23:45)
I checked ScheduledExecutorService, but it only supports executing after specific period from the first run and I don't have any fixed periods, instead I have times from database to execute tasks on.
In a previous question for a different problem here, TimerTask was the solution, but obviuosly I can't make thread a TimerTask as Runnable and TimerTask both have the method run which needs to be implemented. The question here if I make the thread extends TimerTask and have one implementation of run(), would that work?
If not, then how it's possible to do what I'm trying to do?
Use TimerTask .
Create a TimerTask object with a field variable as your thread.
Call the Thread start from the Timer task Run method.
public class SampleTask extends TimerTask {
Thread myThreadObj;
SampleTask (Thread t){
this.myThreadObj=t;
}
public void run() {
myThreadObj.start();
}
}
Configure it like this.
Timer timer new Timer();
Thread myThread= // Your thread
Calendar date = Calendar.getInstance();
date.set(
Calendar.DAY_OF_WEEK,
Calendar.SUNDAY
);
date.set(Calendar.HOUR, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
// Schedule to run every Sunday in midnight
timer.schedule(
new SampleTask (myThread),
date.getTime(),
1000 * 60 * 60 * 24 * 7
);
I think you should better use some library like the Quartz Scheduler. This is basically an implementation of cron for Java.
Have you looked at CountDownLatch from the java.util.concurrent package? It provides a count down then triggers the thread(s) to run. I never needed to use it myself, but have seen it in use a couple times.

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 );

How do I manage Java timer tasks?

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.

Categories