简体   繁体   中英

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

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

Unlike XML configuration or annotation configuration (where you can specify directly a method of a Spring managed bean), you need to create your own Runnable which will call your method.

Say you have the following managed bean:

@Component
public class SchedulingBean{
    public void doSomethingPeriodically(){
    }
}

and you want to run the method inside on a dynamic cron, you have (at least) three options:

Let SchedulingBean implement Runnable and call the doSomehtingPeriodically method from the run method

@Component
public class SchedulingBean implements Runnable{
    public void doSomethingPeriodically(){
}
@Override
public void run(){
    doSomethingPeriodically();
    }
}

Create a new (maybe anonymous) Runnable instance that calls the method from within the managed bean. This could be a little trickier, as you will need to get the reference to that bean from the Spring context.

Or create a new (maybe anonymous) Runnable instance that implements directly the needed functionality, without using a managed bean:

public class SchedulingBean implements Runnable{
    public void doSomethingPeriodically(){
    }
    @Override
    public void run(){
        doSomethingPeriodically();
    }
}

(note the missing @Component )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM