定时任务注解方式:
application2.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <!-- 方式二: 开启IOC注解扫描 --> <context:component-scan base-package="com"/> <!-- 配置定时任务驱动 开启这个配置,spring才能识别 @Scheduled--> <task:annotation-driven/> </beans> |
TaskJob2:
package com.java.task; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class TaskJob2 { private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//定义定时任务方法 @Scheduled(cron="0/2 * * * * ?") public void job1() { System.out.println("定时任务1..."+sdf.format(new Date())); } @Scheduled(cron="0/5 * * * * ?") public void job2() { System.out.println("定时任务2..."+sdf.format(new Date())); } } |
ApplicationTest2:
package com.java.app; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.java.task.TaskJob2; public class ApplicationTest2 { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("application.xml"); TaskJob2 job=(TaskJob2)ac.getBean("taskJob2");
} } |
输出:
定时任务2...2021-06-08 19:09:55 定时任务1...2021-06-08 19:09:56 定时任务1...2021-06-08 19:09:58 定时任务2...2021-06-08 19:10:00 定时任务1...2021-06-08 19:10:00 定时任务1...2021-06-08 19:10:02 定时任务1...2021-06-08 19:10:04 定时任务2...2021-06-08 19:10:05 |
备注:学习笔记