springboot 计划任务Scheduled
从Spring 3.1开始,计划任务在Spring中的实现变得异常的简单。
首先通过在配置类注解@EnableScheduling来开启对计划任务的支持,然后在要执行计划任务的方法上注解@Scheduled,声明这是一个计划任务。
Spring通过@Scheduled支持多种类型的计划任务,包含cron、fixDelay、fixRate等。
计划任务执行类
ScheculeDemo.java
package com.shrimpking;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/8 12:46
* @Scheduled声明该方法是计划任务,
* 使用fixedRate属性每隔固定时间执行。
*/
@Service
public class ScheduleDemo
{
private static final SimpleDateFormat DATE_FORMAT
= new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void getCurrentTime()
{
System.out.println("间隔5秒执行一次:" DATE_FORMAT.format(new Date()));
}
/**
* cron属性可按照指定时间执行,
* 本例指的是每天12点57分执行;
* cron是UNIX和类UNIX(Linux)系统下的定时任务。
*/
@Scheduled(cron = "0 57 12 * * *")
public void fixTimeExecute()
{
System.out.println("在指定时间 " DATE_FORMAT.format(new Date()));
}
}
代码解释
①通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行。
②使用cron属性可按照指定时间执行,本例指的是每天12点57分执行;cron是UNIX和类UNIX(Linux)系统下的定时任务。
配置类
ScheduleConfig.java
package com.shrimpking;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2023/6/8 12:51
* @EnableScheduling注解开启对计划任务的支持。
*/
@Configuration
@ComponentScan("com.shrimpking")
@EnableScheduling
public class ScheduleConfig
{
}
代码解释
①通过@EnableScheduling注解开启对计划任务的支持。
运行
package com.shrimpking;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@SpringBootApplication
public class Springboot49ScheduleApplication
{
public static void main(String[] args)
{
//SpringApplication.run(Springboot49ScheduleApplication.class, args);
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext(ScheduleConfig.class);
}
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhhhjebh
系列文章
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
excel下划线不显示怎么办
PHP中文网 06-23 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel图片置于文字下方的方法
PHP中文网 06-27 -
微信运动停用后别人还能看到步数吗
PHP中文网 07-22