Spring Task开发

在Java的开发过程中,常常用到定时任务,下面简单介绍一下定时任务。

Spring Task

如果你的项目使用spring boot开发,那么可以直接使用spring task开发,Spring 3.0后提供Spring Task实现任务调度,支持按日历调度,相比Quartz功能稍简单,但是在开发基本够用,支持注解编程方式。

具体使用

step1:引入依赖,版本信息可根据项目确认

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${版本信息}</version>
</dependency>

step2:启动类添加@EnableScheduling注解,同时添加注解扫描信息@ComponentScan({"路径1", "路径2"})

@SpringBootApplication
@ComponentScan({"路径1", "路径2"})
@EnableScheduling
public class TestApplication {
    private final static Logger logger = LoggerFactory.getLogger(TestApplication.class);
    public static void main(String[] args) {
        SpringApplication app=new SpringApplication(TestApplication.class);
        app.run(args);
        logger.info("程序启动完毕");
        System.out.println("============启动完毕=============");
    }
}

step3:定义抽象定时任务类信息

@Slf4j
public abstract class AbstractSchedule {
    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    public static final String DEFAULT_CRON = "0 15 11 * * *";
    private String cron = DEFAULT_CRON;

    public void setCron(String cron) {
        System.out.println("AbstractSchedule当前cron="+this.cron+"->将被改变为:" + cron);
        log.info("AbstractSchedule当前cron="+this.cron+"->将被改变为:" + cron);
        this.cron = cron;
    }
}

step4:继承AbstractSchedule类,同时实现SchedulingConfigurer接口

@Slf4j
@Component
@ConditionalOnProperty(name = "schedule.isSchedule", havingValue = "true", matchIfMissing = false)
public class AnnualScheduleService extends AbstractSchedule implements SchedulingConfigurer{

    @Value("${配置文件cron信息}")
    private String cron;

    @Autowired
    private Service aService;

    private ScheduledTaskRegistrar taskRegistrar;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(()->{
            long start = System.currentTimeMillis();
            //你的任务逻辑
            aService.do();
            long end = System.currentTimeMillis();
            log.info("信息>>时间{}", end - start);
            System.out.println("ScheduleService动态修改定时任务cron参数,当前时间:" + dateFormat.format(new Date()));
            log.info("ScheduleService动态修改定时任务cron参数,当前时间:" + dateFormat.format(new Date()));
        },(triggerContext -> {
            CronTrigger trigger = new CronTrigger(cron);
            Date nextExecDate = trigger.nextExecutionTime(triggerContext);
            log.info("nextExecDate:{}", nextExecDate);
            return nextExecDate;
        }));
    }

    @Override
    public void setCron(String cron) {
        System.out.println("ScheduleService当前cron=" + this.cron + "->将被改变为:" + cron);
        log.info("ScheduleService当前cron=" + this.cron + "->将被改变为:" + cron);
        this.cron = cron;
    }
}

备注:定时任务配置信息

#定时任务
schedule:
  cron: cron信息
  #定时任务开关,如果多台部署时,只能有一台服务器配置为true,其他配置为false
  isSchedule: true

在线正则表达式 地址:https://cron.qqe2.com/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容