Run JAVA program at exact times repeatedly using ScheduledExecutorService - java

I want schedule one java program to run at 15th,25th and 45th min of time every hour. For example:
17:15 , 17:25 , 17:45 , 18:15 and so on...
How can I acheive this using ScheduledExecutorService. I can see several examples which can trigger scripts after certain time intervals with respect to the time they are triggered using ScheduledExecutorService.
Can anyone suggest me relevent links and examples to get some idea

I could not find a way to schedule a Timer with uneven intervals. However, it is relatively straightforward to schedule a Timer to execute at fixed intervals.
For your case, you could schedule three timers, one for :15, one for :25, and one for :45 past the hour:
public class TaskTest {
public static scheduleTask(int interval) {
GregorianCalendar cal = new GregorianCalendar();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int hourScheduled = hour;
// if we are past the scheduled time then schedule for the next hour
if (minute > interval) {
++hourScheduled;
}
cal.set(year, month, date, hourScheduled, interval);
long initialDelay = cal.getTimeInMillis() - System.currentTimeMillis();
if (initialDelay < 0) {
initialDelay = 0L;
}
// schedule each job for once per hour
int period = 60*60*1000;
Timer timer = new Timer();
SomeTask someTask = new SomeTask();
timer.scheduleAtFixedRate(someTask, initialDelay, period);
}
public static void main(String[] args) {
// schedule for the 15th, 25th and 45th min of time every hour
scheduleTask(15);
scheduleTask(25);
scheduleTask(45);
}
}
public class SomeTask extends TimerTask {
#Override
public void run() {
// do something
}
}

You want to trigger your code at some time point, not periodically, I think there are several choices:
if your program run under Linux or other systems which support crontab, then crontab is a good choice.
We could create multi cron job to achieve your target:
use command "crontab -e" to edit cron jobs:
15 * * * * /java_path/java your_program parameters
25 * * * * /java_path/java your_program parameters
35 * * * * /java_path/java your_program parameters
45 * * * * /java_path/java your_program parameters
if you don't want to use crontab, and you just want a pure java solution, quartz will help you.
quartz could let you configure cron triggers which are little like crontab under Linux.
please refer to http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/tutorial-lesson-06.html to get more information.
At last, you want a pure java, and lightweight solution, you could simply use Java Timer and TimerTask, such as:
public class App {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask tt = new SchedulerTask();
DateFormat df = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
Date triggerTime = null;
try {
triggerTime = df.parse("2016-04-12 13:15:00");
} catch (ParseException e) {
e.printStackTrace();
}
timer.schedule(tt, triggerTime, 3600*1000);
}
static class SchedulerTask extends TimerTask {
#Override
public void run() {
System.out.println("I am running at " + Calendar.getInstance().getTime());
}
}
}
you could create 4 tasks like the task above, trigger at 13:15, 13:25, 13:35, 13:45 and each task runs once for every hour.

You can schedule same runnable with fixed 1hour interval & delay should be variable based on current time.
Example current time 6:10 than delay for your first schedule will be 5min(6:15), for second schedule 5+10=15 min(6:25).
like that you can create multiple schedule each with one hour delays.
import java.util.GregorianCalendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MultipleScheduler {
public static void main(String[] args) {
Runnable task = new Runnable() {
#Override
public void run() {
System.out.println(System.currentTimeMillis() + " Task executed");
}
};
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
int BaseDelay = getInitialDelay();
service.scheduleAtFixedRate(task, BaseDelay, 60, TimeUnit.MINUTES);
service.scheduleAtFixedRate(task, BaseDelay + 10, 60, TimeUnit.MINUTES);
service.scheduleAtFixedRate(task, BaseDelay + 30, 60, TimeUnit.MINUTES);
}
static int getInitialDelay() {
GregorianCalendar cal = new GregorianCalendar();
int minute=cal.get(cal.MINUTE);
int delay=0;
//some logic to calculate delay updated delay should be returned
return delay;
}
}

Related

Printing the number of files in a directory hourly in JAVA

Suppose in a directory there are N number of files, we need to display/log the number of files present after every one hour.
ex: No of files at 10:00 AM :25
No of files at 11:00 AM :22
so we need to create a timed action, I thought of using Thread.sleep(XXX) to suspend the Thread for 1 hour and then again get the count and print.
please suggest better alternatives.
Use TimerTask - A task that can be scheduled for one-time or repeated execution by a Timer.
import java.io.File;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimeIt {
public static void main(final String[] args) throws InterruptedException {
final TimerTask task = new TimerTask() {
#Override
public void run() {
System.out.println("Task performed on " + new Date());
// Complete lo
final int count = new File("/tmp/").list().length;
System.out.println(count);
}
};
final Timer timer = new Timer("Timer");
timer.scheduleAtFixedRate(task, 1000L, 1000L);
Thread.sleep(1000L * 2);
timer.cancel();
}
}
TimerTask Java Doc
Java Timer and TimerTask

Run a job for every one hour in java thread

I have to run a job using a thread for every 1 hour. This job is to read files in a folder. I have created a simple thread
Thread t = new Thread() {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000*60*60);
//Implementation
} catch (InterruptedException ie) {
}
}
}
};
t.start();
which runs every one hour so that I can call the function to read the files. I want to know if this approach is good or any other approach is good
You can use ScheduledExecutorService for this task, and here is a Sample Example
If you want to use just Thread then try
try {
Thread.sleep(1000 * 60 * 60);
} catch (InterruptedException ex) {}
otherwise its a good choice that you can go with ScheduledExecutorService
ScheduledExecutorService executor = ...
executor.scheduleAtFixedRate(someTask, 0, 1, TimeUnit.HOUR);
import java.util.Timer;
import java.util.TimerTask;
public class MyTimer {
public static void main(String[] args) {
OneHourJob hourJob = new OneHourJob();
Timer timer = new Timer();
timer.scheduleAtFixedRate(hourJob, 0, 5000 * 60 * 60); // this code
// runs every 5 seconds to make it one hour use this value 5000 * 60 *
// 60
}
}
class OneHourJob extends TimerTask {
#Override
public void run() {
System.out.println("Ran after one hour.");
}
}
Above code runs every five seconds. Whatever work you need to do write that code in run method of OneHourJob

run a scheduled task once a day

My requirement is I want to schedule a task that should run once a day.For that I am using following code:
public class setAutoReminder {
EscalationDAO escalationDAO=new EscalationDAO();
final SendMail sendMail=new SendMail();
public void fetch(){
Date date=new Date();
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
int number=escalationDAO.getAutoReminder();
System.out.println(number);
if(number>0) {
sendMail.sendMail();
}
}
},date, 1000000000);
}
}
but this code runs multiple times.I want it to runs once a day.What should I do?
If you don't have many scheduled jobs then don't add all the Spring baggage.
Keep it simple.
Date date=new Date();
Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
System.out.println("Im Running..."+new Date());
}
},date, 24*60*60*1000);//24*60*60*1000 add 24 hours delay between job executions.
This will do the stuff.
-Siva
With Spring (using lombok #Slf4j):
#Slf4j
#Component
public class SetAutoReminder
{
#Autowired
private EscalationDAO escalationDAO;
#Autowired
private SendMail sendMail;
#Scheduled(cron = "0 0 0 * * *") // everyday at midnight
public void fetch(){
final int number = escalationDAO.getAutoReminder();
log.debug("Today number: {}", number);
if (number>0) {
sendMail.sendMail();
}
}
}
Tutorial on spring scheduling: springsource blog
You need a scheduler, like Quartz Scheduler

Creating delay between measurements

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

How to run a method at XX:XX:XX time?

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.

Categories