springboot--定时器
2021-05-12 08:27
标签:dex src ima 策略 sys value turn policy tran 1、启动类加上注解 @EnableScheduling 2、导入jar包 3、创建定时器业务类 4、创建定时配置类 5、在yml中进行配置 springboot--定时器 标签:dex src ima 策略 sys value turn policy tran 原文地址:https://www.cnblogs.com/xuemeng11/p/13140732.html
druidpackage com.ccc.demoboot.task;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
public class lx implements Runnable{
private Log logger=LogFactory.getLog(lx.class);
@Override
public void run() {
System.out.println("定时器任务1");
logger.info("任务一执行成功");
}
}
package com.ccc.demoboot.conf;
import com.ccc.demoboot.task.lx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class TaskConf implements SchedulingConfigurer {
@Value("${lx.cron}")
private String lxScon;
@Autowired
private lx lxTask;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.setTaskScheduler(getTaskScheduler());
scheduledTaskRegistrar.addCronTask(lxTask,lxScon);
}
@Bean
public TaskScheduler getTaskScheduler(){
//创建定时任务调度线程池
ThreadPoolTaskScheduler taskScheduler=new ThreadPoolTaskScheduler();
//设置线程名称前缀
taskScheduler.setThreadNamePrefix("定时任务");
//设置线程池大小,根据任务来确定
taskScheduler.setPoolSize(10);
//线程关闭最大等待时间
taskScheduler.setAwaitTerminationSeconds(60);
//线程关闭时等待所有任务完成
taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
// 任务丢弃策略
taskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
return taskScheduler;
}
}
lx:
#cron: 0 0 0 1/1 * ? #每隔1天执行一次
cron: 0 */1 * * * ? #每隔1分钟执行一次
#cron: 0 0 0/1 * * ? #每隔1小时执行一次