版权声明:有一种生活不去经历不知其中艰辛,有一种艰辛不去体会,不会知道其中快乐,有一种快乐,没有拥有不知其中纯粹 https://blog.csdn.net/wwwzydcom/article/details/82888776
第一种方式:基于XML方式进行任务调度处理
在线cron表达式生成
sping.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:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
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/task
http://www.springframework.org/schema/task/spring-task.xsd">
<!--定义的规范-->
<context:component-scan base-package="com" />
<!--配置定时调度任务-->
<task:scheduled-tasks>
<task:scheduled ref="jobService" method="job01" cron="0/5 * * * * ? "/>
</task:scheduled-tasks>
</beans>
package com;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class JobService {
public void job01(){
System.out.println("jb01---->"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
package com;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main (String[] args){
new ClassPathXmlApplicationContext(“sping01.xml”);
}
}
第二种:基于注解的方式进行任务调度处理
spring02.xml:加入 <task:annotation-driven />
<?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:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
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/task
http://www.springframework.org/schema/task/spring-task.xsd">
<!--定义的规范-->
<context:component-scan base-package="com" />
<!--自动配置定时调度任务-->
<task:annotation-driven />
</beans>
方法前加 @Scheduled(cron = “0/2 * * * * ?”)
package com;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class JobService {
@Scheduled(cron = "0/2 * * * * ?")
public void job01(){
System.out.println("jb01---->"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
package com;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main (String[] args){
new ClassPathXmlApplicationContext("spring02.xml");
}
}