首先配置spring-context.xml文件java
在xmlns 下加以下代码spring
xmlns:task="http://www.springframework.org/schema/task"
在xsi:schemaLocation里添加以下代码数据库
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
还有任务扫描服务器
<task:annotation-driven />
以上配置完成,新建java类写定时任务测试
package com.test.job; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import lombok.extern.log4j.Log4j2; /** * 定时任务测试 * @author ljl * */ @Log4j2 @Component public class TestJob { @Scheduled(cron = "0 */5 * * * ?") public void test1() { log.info("每5分钟执行一次"+ new Date()); } @Scheduled(cron = "0 0 12 * * ?") private void test2() { log.info("天天中午12点执行"+ new Date()); } }
以上定时任务完成。spa
思考:若是多台服务器部署同一个项目,就会出现一个定时任务屡次执行的问题,如何解决?线程
网上找了如下四种方法,能够做为参考。code
一、设置执行定时任务的机器名,在代码中判断,只让某一台机器执行。server
二、若是有可能,将定时任务独立出来,成为一个单独的项目工程,单一部署。xml
三、将任务的定时触发模块、任务的执行模块分离。任务的定时触发模块每台机器都容许触发任务,可是任务的执行模块,只要收到一个执行任务,那么下一个执行任务就被忽略掉。任务开始执行设置running = true,任务执行完毕设置running = false,当running