第一步:定义两个类java
Task3spring
package group.esperanto.util; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component //必须标记为一个Spring管理的JavaBean类 public class MyTask3 { //不须要继承任何子类 @Scheduled(fixedRate=2000) //设置为两秒一执行 间隔触发 public void excJob() { System.out.println("【MyTask3】当前日期: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } }
Task4app
package group.esperanto.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component //必须标记为一个Spring管理的JavaBean类 public class MyTask4 { @Scheduled(cron="* * * * * ?" ) // 一秒一执行 定时触发 public void excJob() { try{ // 休息5秒再继续执行 TimeUnit.SECONDS.sleep(5); }catch (Exception e) { } System.out.println("【MyTask4】当前日期: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } }
第二步:修改applicationContext文件code
<task:annotation-driven/> <!-- 定义一个任务调度池,可并行调度20个任务 --> <task:scheduler id="schedulerPool" pool-size="20"/> <context:annotation-config/> <context:component-scan base-package="cn.mldn"/>