abipc
abipc

Reputation: 1035

Java TimerTask - Run a task at XX:MM hours everyday

Using Timer and TimerTask.

Not able to understand why is this configuration starting the task immediately on deployment (using this in a web based Spring app). It should be started at today.getTime and then must repeat every day.

    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 3);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);

    MyTask task = new MyTask();
    Timer timerJob = new Timer();
    timerJob.schedule(task, today.getTime(), 
             TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); 

Upvotes: 1

Views: 216

Answers (1)

Medet Koilybay
Medet Koilybay

Reputation: 111

I think, it would be better to use CronTrigger or Trigger with 24hours repeat interval.

Example of CronTrigger:

public class CronTriggerRunner {

public static void main(String args[]) throws SchedulerException, Exception {

    SchedulerFactory schedulerFactory = new StdSchedulerFactory();

    Scheduler scheduler = schedulerFactory.getScheduler();

    JobDetail job = JobBuilder.newJob(ClassToRun.class).withIdentity("jobName", "group").build();
    // Starting CronTrigger
    String exp = "0 0 9 * * ?"; //trigger format, everyday at 9:00 am

    Trigger trigger = TriggerBuilder.newTrigger()
                                .startNow()
                                .withSchedule(
                                     CronScheduleBuilder.cronSchedule(exp))
                                .build();

    // Planning job detail
    scheduler.scheduleJob(job, trigger);

    // starting scheduler
    scheduler.start();
}
}

ClassToRun.java

public class ClassToRun implements Job {

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try{
        //doSomething
    }
    catch(Exception e){
        e.printStackTrace(System.out);
    }
  }
}

Everyday at 9:00 am, public void execute() function will doSomething :D

Hope this will help. Please let me know.

EDIT: You need to download and add 2 jar files. 1) quartz-2.2.1.jar 2) slf4j-api-1.6.6.jar

Upvotes: 1

Related Questions