Spring定时任务 @Scheduled注解(多实例支持)

Springboot 版本的请参考这篇博客Spring boot 自带的Schedule–多实例
shedlock锁的更多使用方式请参考github ShedLock

  1. 添加pom
  2. 数据库脚本
  3. 修改配置文件
  4. 测试类

一. 添加pom

因为要使用多实例调度,所以我是用了分布式锁shedlock,Spring pom请自行添加


 
   net.javacrumbs.shedlock
    shedlock-spring
    1.0.0


    net.javacrumbs.shedlock
    shedlock-provider-jdbc-template
    1.0.0


    net.javacrumbs.shedlock
    shedlock-provider-jdbc
    1.0.0

二. 数据库脚本

创建shedlock表,shedlock用

CREATE TABLE shedlock(
    name VARCHAR(64), 
    lock_until TIMESTAMP(3) NULL, 
    locked_at TIMESTAMP(3) NULL, 
    locked_by  VARCHAR(255), 
    PRIMARY KEY (name)
) 

三. 修改配置文件

Spring定时任务 @Scheduled注解(多实例支持)_第1张图片
如图,在xml中添加途中4行

http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd
xmlns:task="http://www.springframework.org/schema/task


		

并添加如下配置(shedlock)



    



    
        
    
    
    
        
            
        
    

四. 测试类

import net.javacrumbs.shedlock.core.SchedulerLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


@Service
@EnableScheduling
public class ScheduleController {
    private final static Logger logger = LoggerFactory.getLogger(ScheduleController.class);
    private static final long FOURTEEN_MIN = 4 * 1000;

    @Scheduled(cron = "0/5 * * * * ?")
    @SchedulerLock(name = "eoaCall", lockAtLeastFor = FOURTEEN_MIN, lockAtMostFor = FOURTEEN_MIN)
    public void schdule() {
        logger.info("============== start ================"+new Date());
    }
}

你可能感兴趣的:(spring)