Java 如何使用calendar对象在spring scheduler中调度任务?
我正在开发一个基于spring的web应用程序。要求如下:Java 如何使用calendar对象在spring scheduler中调度任务?,java,spring,spring-mvc,spring-scheduled,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+"
用户输入日期(以字符串格式)。
为该日期安排任务(仅一次) 我的代码是:
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**)
我怎样才能做到这一点?您可以将此用于逐步指南
基本上,您需要一个CronTrigger
对象,然后需要以编程方式从数据库中设置trigger.setCronExpression
。您可以使用
与Springbean类似&代码来自:
你能提供完整的代码吗?因为,我是spring的新手&你没有使用Schedule annotationRunnable()和run()显示错误。。。说Runnable()--改为java.lang&run()--从编辑中删除@Override annotationmy代码以澄清问题您不能使用注释。有了注释,您需要在源代码中提供cron计划。但你只有在用户输入信息时才能得到这些信息。@Andrew Spencer感谢Andrew。你能提供代码或源代码来实现这一点吗?…请参见Spring文档第28.3.2节中的一个例子:但这就是Harden Zhang已经给你的Runnable()和run()显示错误的内容。。。。
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();
}