如何使用日历对象在spring scheduler中安排任务?

时间:2015-06-02 07:16:22

标签: java spring spring-mvc spring-scheduled

我正在开发一个基于spring的Web应用程序。要求如下:
用户输入日期(字符串格式)。
为该日期安排任务(仅限一次)

我的代码是:

calendar.setTime(formatter.parse(dateFromForm));
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
.
.
String cornExp = "0 "+minutes+" "+hours+" "+day+" "+month+" "+year;

我想将cornExp值传递给:

@Scheduled(cron=**cornExp**)  

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以将此link用于分步指南

基本上,您需要一个CronTrigger对象,然后需要以编程方式从数据库中设置trigger.setCronExpression

答案 1 :(得分:0)

您可以使用ThreadPoolTaskScheduler

像这样的春天Bean&来自springside project的代码:

ThreadPoolTaskScheduler threadPoolTaskScheduler;
@PostConstruct
public void start() {
    .
    .
    calendar.setTime(formatter.parse(dateFromForm));
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int month = calendar.get(Calendar.MONTH);
    .
    .
    final String cornExp = "0 "+minutes+" "+hours+" "+day+" "+month+" "+year;

    threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.setThreadNamePrefix("SpringCronJob");
    threadPoolTaskScheduler.initialize();

    threadPoolTaskScheduler.schedule(new Runable(){
        @Override
        public void run() {
            //run task
            //...
        }
    }
         , new CronTrigger(cornExp));
}

@PreDestroy
public void stop() {
    ScheduledExecutorService scheduledExecutorService = threadPoolTaskScheduler.getScheduledExecutor();
    scheduledExecutorService.shutdown();
}