方法一:
<context:annotation-config />
<!--spring扫描注解的配置 -->
<context:component-scan base-package="com.baodian.bdweb.timer" />
<bean id="Taskaa" class="com.baodian.bdweb.timer.Taskaa" />
<bean id="Taskbb" class="com.baodian.bdweb.timer.Taskbb" />
<task:scheduled-tasks>
<task:scheduled ref="Taskaa" method="show" cron="01 38 15 * * ?" />
<task:scheduled ref="Taskbb" method="show" cron="01 39 15 * * ?" />
</task:scheduled-tasks>
---------------------
@Component("Taskaa")
public class Taskaa{
@Scheduled
public void show(){
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Taskaa:"+s.format(new Date()));
}
}
---------------------
@Component("Taskbb")
public class Taskbb{
@Scheduled
public void show(){
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Taskbb:"+s.format(new Date()));
}
}
---------------------
方法二:
<!-- 计划任务配置,用 @Service @Lazy(false)标注类,用@Scheduled(cron = "0 0 2 * * ?")标注方法 --> <task:executor id="executor" pool-size="10" /> <task:scheduler id="scheduler" pool-size="10" /> <task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true" />
package com.hhwy.fm.statisticalanalysis.subcontractproduction.job; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.CronTrigger; import org.springframework.stereotype.Component; import java.util.*; @Component public class SubcontractProductionJob implements SchedulingConfigurer { //设置任务执行时间轮转,cronExpression表达式 (秒 分 时 日 月 周) @Value("${TASK_DYNAMIC_CRON}") private String dynamicCron; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask(new Runnable() { @Override public void run() { //业务逻辑处理 } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { CronTrigger trigger = new CronTrigger(dynamicCron); Date nextExec = trigger.nextExecutionTime(triggerContext); return nextExec; } }); } }