Advertisements

Create a scheduler task in 5 simple steps – java

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.

Advertisements

About harryjoy
A passionate self-taught software developer. Currently working as Lead Software Engineer in an IT company.

2 Responses to Create a scheduler task in 5 simple steps – java

  1. Sreedevi K says:

    Hi Harry, quartz.jar is not existing in the server. Could you please add it back.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: