0
点赞
收藏
分享

微信扫一扫

SpringBoot 定时任务

求阙者 2023-01-29 阅读 118

示例

# 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/​​

 



举报

相关推荐

0 条评论