SpringBoot Job计划任务定时器

SpringBoot 定时器(Fu++聚合支付收款云平台

1、从Spring 3.1 开始,计划任务在Spring中的实现变得异常的简单。首先通过在配置类注解 @EnableScheduling 来开启对计划任务的支持,然后再执行集合任务的方法上注解 @Scheduled ,声明这是一个计划任务。

2、Spring 通过 @Scheduled 支持多种类的计划任务,包含cronfixDelayfixRate等。
计划任务执行代码,参考:

package com.cenobitor.scheduler.taskscheduler;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)//1
    public void reportCurrentTime(){
        System.out.println("每隔五秒执行一次 "+DATE_FORMAT.format(new Date()));
    }

    @Scheduled(cron = "0 05 18 ? * *")//
    public void fixTimeExecution(){
        System.out.println("在指定时间 "+DATE_FORMAT.format(new Date())+"执行");
    }
}

①、通 @Sceduled 声明该方法是计划任务,使用 fixedRate 属性每隔固定时间执行。
②、使用 cron 属性可按照指定时间执行,本例指每天18点05分执行。

3、配置运行计划任务,参考:

package com.cenobitor.scheduler;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SchedulerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulerApplication.class, args);
    }
}

:使用 @EnableScheduling 注解开启对计划任务的支持。

运行结果:
每隔五秒执行一次 22:01:54
每隔五秒执行一次 22:01:59
在指定时间 18:05:00执行
每隔五秒执行一次 22:02:04

OK!!大功告成!!

猜你喜欢

转载自blog.csdn.net/fujaja/article/details/81563531