spring周期任务(代码模板)
package cn.changemax.application.job;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
* @author WangJi
* @Description 周期任务模板
* @Date 2019/11/4 16:28
*/
@Log4j2
@Component
@EnableScheduling
public class PeriodicTaskJob {
/**
* 锁超时时间,防止线程在入锁以后,无限的执行等待
*/
private int expireMsecs = 10 * 60 * 1000;
/**
* 锁等待时间,防止线程饥饿
*/
private int timeoutMesecs = 1 * 1000;
@Transactional(rollbackFor = Exception.class)
@Scheduled(cron = "0 0/10 * * * ?")
public void execute() {
Date nowDate = new Date();
String lockKey = "PERIODIC_TASK_JOB_KEY";
RedisLock lock = new RedisLock(redisTemplate, lockKey, timeoutMesecs, expireMsecs);
if (!lock.lock()) {
log.info(() -> "其他任务正在运行中");
return;
}
try {
long startTime = System.currentTimeMillis();
//逻辑代码.....
lock.unlock();
long endTime = System.currentTimeMillis();
log.info(() -> "周期任务结束,本次耗时:" + (endTime - startTime) + "毫秒");
} catch (ReadAppletsException e) {
e.printStackTrace();
log.error(() -> "周期任务发生异常:" + e.getMessage());
lock.unlock();
} catch (Exception e) {
e.printStackTrace();
log.error(() -> "周期任务发生异常:" + e.getMessage());
lock.unlock();
}
}
}
上面很清楚了,直接编写你的周期任务代码内容就是了。前提要依赖于redis

浙公网安备 33010602011771号