Most people don’t know how to run some specific task at specific time in java. For example send daily email at 11:59 or do a daily wind up job or weakly database clean up job, etc. So here you will find how to schedule task in java in 5 simple steps.
Before starting first you need to download quartz jar. You can download it from here.
Step-1 Make a class that implements Job interface from quartz jar and implement it’s execute method. In this method define your task that will be executed on time interval.
public class ScheduleTaskHelper implements Job { public void execute(JobExecutionContext arg0) throws JobExecutionException { // define your task here. } }
Step-2 Create another class which will create and start scheduler for this task.
public class ScheduleTask{ public ScheduleTask()throws Exception{ } }
Step-3 To start scheduler task we first need to define a SchedulerFactory and a Scheduler. Following code will do that:
SchedulerFactory sf=new StdSchedulerFactory(); Scheduler sched=sf.getScheduler();
Step-4 Start that scheduler which is done by calling start method of Scheduler as follows:
sched.start();
Step-5 Create a Job of our task, a cron trigger to tell on which time interval it will run and schedule that job in the scheduler.
JobDetail jd=new JobDetail("myjob", Scheduler.DEFAULT_GROUP,ScheduleTaskHelper.class); CronTrigger tr=new CronTrigger("myCronTrigger", Scheduler.DEFAULT_GROUP,"0 59 23 ? * *"); sched.scheduleJob(jd, tr);
Note: – Here the string “0 59 23 ? * *” is used to define scheduler time that is on which time our scheduled task will run. Here this string will schedule task that will run daily in 11:59 pm. To know how to write appropriate cron trigger string refer to this.
Hi Harry, quartz.jar is not existing in the server. Could you please add it back.
Hi Sreedevi,
Thanks for pointing it out. Updated link to latest stable release.
Thanks & Regards.