Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule task in java code

I know how to schedule task in spring context:

  <task:scheduler id="taskScheduler" pool-size="1" />
  <task:scheduled-tasks scheduler="taskScheduler">
    <task:scheduled ref="jobWatcher" method="run" cron="*/10 * * * * ?" />
  </task:scheduled-tasks>

But cron of my task can by configured during runtime so I need to create task in java code. In spring docs: http://docs.spring.io/spring/docs/3.0.x/reference/scheduling.html is something like this:

scheduler.schedule(task, new CronTrigger("* 15 9-17 * * MON-FRI"));

which is what I want but I have no idea how their create scheduler in this example and what is his class. Please help

like image 280
hudi Avatar asked Nov 01 '22 11:11

hudi


1 Answers

Just three paragraph above in your link

public interface TaskScheduler {

    ScheduledFuture schedule(Runnable task, Trigger trigger);

    ScheduledFuture schedule(Runnable task, Date startTime);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);

}

so in scheduler.schedule(task, new CronTrigger("* 15 9-17 * * MON-FRI"));

  • scheduler is an instance of TaskScheduler
  • task is a Runnable

    Runnable exampleRunnable = new Runnable(){
    
        @Override
        public void run() {
            //To change body of implemented methods 
        }
    };
    
like image 66
RamonBoza Avatar answered Nov 04 '22 12:11

RamonBoza