How to schedule task in java code

强颜欢笑 提交于 2019-12-19 19:54:07

问题


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


回答1:


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



回答2:


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)



来源:https://stackoverflow.com/questions/19833279/how-to-schedule-task-in-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!