I need to do a periodic operation (call a java method) in my web app (jsp on tomcat).
How can i do this ? Java daemon or others solutions ?
You could use a ScheduledExecutorService for periodic execution of a task. However, if you require more complex cron-like scheduling then take a look at Quartz. In particular I'd recommend using Quartz in conjunction with Spring if you go down this route, as it provides a nicer API and allows you to control your job firing in configuration.
ScheduledExecutorService Example (taken from Javadoc)
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
Adams answer is right on the money. If you do end up rolling your own (rather than going the quartz route), you'll want to kick things off in a ServletContextListener. Here's an example, using java.util.Timer, which is more or less a dumb version of the ScheduledExexutorPool.
public class TimerTaskServletContextListener implements ServletContextListener
{
private Timer timer;
public void contextDestroyed( ServletContextEvent sce )
{
if (timer != null) {
timer.cancel();
}
}
public void contextInitialized( ServletContextEvent sce )
{
Timer timer = new Timer();
TimerTask myTask = new TimerTask() {
#Override
public void run()
{
System.out.println("I'm doing awesome stuff right now.");
}
};
long delay = 0;
long period = 10 * 1000; // 10 seconds;
timer.schedule( myTask, delay, period );
}
}
And then this goes in your web.xml
<listener>
<listener-class>com.TimerTaskServletContextListener</listener-class>
</listener>
Just more food for thought!
Related
I need to execute a certain task periodically within a certain timeout.
But dependent on the result of the task, I want to stop before the end of the timeout is reached. And in addition I need a reference to the currently executed task in order to have the chance to ask for the result.
Solution to 1) is no problem, because it can be solved with the little code snipped shown below. But I can not figure out how to integrate 2). So with this code example, I would like that the beeper object runs code which can have a positive or a negative result and based on (for example) a positive result, the beeper task should no longer be executed periodically.
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
In your run method if condition is fulfilled then invoke scheduler.shutdown(). That should do exactly what you want.
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
if(isMyCondition() {
scheduler.shutdown();
}
}
};
See javadoc for ExecutorService.shutdown()
I have some type of task for example in a loop with same method but different arguments,
I need to execute these tasks in one after another in some intervals,
and all this activity need to be execute in again and again in a particular schedule,
e.g. let say I have a method called
public void GetData(String tablename){
}
so first time I will provide table1 then table2 then table3.....
similar to for loop but need some interval in between,
and same above all execution need to execute in each 10 min,
sample code I have implemented as
final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
final Runnable runner = new Runnable() {
public void run() {
getData(String table);
}
};
final ScheduledFuture<?> taskHandle =
scheduler.scheduleAtFixedRate(runner, 1, 10, SECONDS);
its working fine for one table for need help and best way to implement for multiple tables.
tryjava.util.Timer to schedule a task to execute
public class ReminderBeep {
Toolkit toolkit;
Timer timer;
public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new ReminderBeep(5);
System.out.println("Task scheduled.");
}
}
You can just use Thread.sleep() in your loop (if it's not on the main thread). Something like this (the code is not tested so may contain errors):
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
public void run() {
getData(String table);
}
Thread.sleep(10000);
}
I have a program which reads Inbox messages from email accounts, as the title says i would like to run the program after every 1.5hrs.
Is there any OS(Windows and Linux) level or JVM level solution which would help in performing the task.
Thanks.
On Windows use the at command or "Scheduled Jobs", on Linux use a cron job.
http://support.microsoft.com/kb/313565
http://en.wikipedia.org/wiki/Cron
Taken from javadoc of ScheduledExecutorService:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
Create a cron job.
Type crontab -e
and add an entry for your command.
I am trying to make a set of measurements of signal strength, so i want to make a delay between same method (that return needed value) execution - value1...delay....value2....delay.... Currently i am using
Thread.sleep(DELAY);
Such way of creating the delay seems to work, but as I understood it makes the whole app to stop. I have looked through Android Developers website and found some other ways using Timer and ScheduledExecutorService. But i do not fully understand how to create a delay using those 2 ways. May be someone will be some kind and give me some ideas or directions to start with?
You could use a Runnable and a handler.
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
// Get the difference in ms
long millis = SystemClock.uptimeMillis() - mStartTime;
// Format to hours/minutes/seconds
mTimeInSec = (int) (millis / 1000);
// Do your thing
// Update at the next second
mHandler.postAtTime(this, mStartTime + ((mTimeInSec + 1) * 1000));
}
};
And start this with a handler:
mHandler.postDelayed(mUpdateTimeTask, 100);
Ofcourse you have to have a global mHandler (private Handler mHandler = new Handler();) and a starting time (also the uptimeMillis). This updates every second, but you can change it for a longer period of time.
http://developer.android.com/reference/android/os/Handler.html
java.util.concurrent.Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new java.lang.Runnable()
{
#Override
public void run()
{
System.out.println("call the method that checks the signal strength here");
}
},
1,
1,
java.util.concurrent.TimeUnit.SECONDS
);
This is the snippet of code which will call some method after initial delay of 1 second every 1 second.
There is a tutorial about how to create a simple android Countdown timer. You can take a look, this may help.
To use Timer you create a Timer instance
Timer mTimer = new Timer();
Now the task you wish to run can be scheduled.
mTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
//THE TASK
}
}, DELAY, PERIOD);
DELAY = amount of time in milliseconds before first execution.
LONG = amount of time in milliseconds between subsequent executions.
See here for more.
The documentation page for ScheduledExecutorService gives a good example of how to use it:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};
// Run the beeper Runnable every 10 seconds after a 10 second wait
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate( beeper, 10, 10, SECONDS ) ;
// Schedule something to cancel the beeper after an hour
scheduler.schedule( new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
}
HI
I want to run a method in my program evry X hours, how to do that ?
Im googling and there is nothing :/
You could consider Quartz.
It is some sort of cron that runs inside java. I admit though that it is probably an overkill if you want to schedule only one job.
You could take a look at the Timer class, but the best option is to use a ScheduledExecutorService:
e.g. This will beep at a scheduled rate:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
}
I use the Quartz framework for most of my scheduling ( http://www.quartz-scheduler.org/ ) but if you're doing something simple, java.util.Timer is fine.
// in a class body...
public static void main( String[] argv ) {
Timer timer = new Timer();
int secondsBetweenRuns = 3600;
timer.schedule( new MyOwnTask(), 0, secondsBetweenRuns * 1000 );
}
static class MyOwnTask extends TimerTask {
public void run() {
doWhateverYouNeedToDoEveryHour();
}
}
Scheduled Task (in Windows) or Cron (in Unix)
You could save the time at a certain point, than start a timer. When the time is up, you run the method and restart the timer.