SpringBoot 定时任务

示例

# ScheduledTaskService.java

package com.ln.myboot3.schedule;

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 dateFormat = new SimpleDateFormat("HH:mm:ss");
    private ScheduledTaskService() {
        System.out.println("ScheduledTaskService Construct.......");
    }


    @Scheduled(fixedRate = 5000) //通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行
    public void reportCurrentTime() {
        System.out.println("每隔5秒执行一次 " + dateFormat.format(new Date()));
    }

    @Scheduled(cron = "0 07 20 ? * *") //使用cron属性可按照指定时间执行,本例指的是每天20点07分执行
    //cron是UNIX和类UNIX(Linux)系统下的定时任务
    public void fixTimeExecution() {
        System.out.println("在指定时间 " + dateFormat.format(new Date()) + " 执行");
    }

    @Scheduled(cron = "0/10 * * * * ?")
    public void init() {
        this.prepare();
    }

    public void prepare() {
        System.out.println("=== 每10s执行一次,now time:" + dateFormat.format(new Date()));
    }
}

#配置 TaskScheduleConfig

package com.ln.myboot3.schedule;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;

@Configuration
@ComponentScan()
@EnableScheduling
public class TaskScheduleConfig {
    @Bean
    public TaskScheduler taskScheduler() {
        return new ConcurrentTaskScheduler();
    }
}

# 启动 Myboot3Application

package com.ln.myboot3;

import com.ln.myboot3.schedule.TaskScheduleConfig;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@SpringBootApplication
public class Myboot3Application {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskScheduleConfig.class);
    }

}

 

cron含义

[秒] [分] [时] [日] [月] [周] [年]

线上工具: https://cron.qqe2.com/

 

posted @ 2023-01-26 09:09  jihite  阅读(157)  评论(0编辑  收藏  举报