Spring计划任务怎么用

发布时间:2021-09-28 11:06:05 作者:小新
来源:亿速云 阅读:124

这篇文章给大家分享的是有关Spring计划任务怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

具体如下:

一 点睛

从Spring3.1开始,计划任务在Spring中的实现变得异常的简单。只需要下面两步。

1 通过在配置类上注解@EnableScheduling来开启对计划任务的支持。

2 在要执行计划任务的方法上注解@Scheduled,声明这是一个计划任务。

Spring通过@Scheduled支持多种类型的计划任务,包含cron、fixDelay、fixRate等。

二 实战

1 配置类

package com.wisely.highlight_spring4.ch4.taskscheduler;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableScheduling;@Configuration@ComponentScan("com.wisely.highlight_spring4.ch4.taskscheduler")@EnableScheduling //1public class TaskSchedulerConfig {}

2 计划任务执行类

package com.wisely.highlight_spring4.ch4.taskscheduler;import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Service;@Servicepublic class ScheduledTaskService {   private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");   @Scheduled(fixedRate = 5000) //该方法是计划任务,使用fixedRate属性每隔固定时间执行。   public void reportCurrentTime() {      System.out.println("每隔五秒执行一次 " + dateFormat.format(new Date()));    }   @Scheduled(cron = "0 28 11 ? * *" ) //每天11点28分执行   public void fixTimeExecution(){     System.out.println("在指定时间 " + dateFormat.format(new Date())+"执行");   }}

3 主类

package com.wisely.highlight_spring4.ch4.taskscheduler;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {   public static void main(String[] args) {      AnnotationConfigApplicationContext context =           new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);   }}

三 运行结果

每隔五秒执行一次 19:58:50

每隔五秒执行一次 19:58:55

每隔五秒执行一次 19:59:00

每隔五秒执行一次 19:59:05

每隔五秒执行一次 19:59:10

每隔五秒执行一次 19:59:15

每隔五秒执行一次 19:59:20

每隔五秒执行一次 19:59:25

每隔五秒执行一次 19:59:30

每隔五秒执行一次 19:59:35

每隔五秒执行一次 19:59:40

每隔五秒执行一次 19:59:45

每隔五秒执行一次 19:59:50

每隔五秒执行一次 19:59:55

每隔五秒执行一次 20:00:00

每隔五秒执行一次 20:00:05

感谢各位的阅读!关于“Spring计划任务怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. cron计划任务
  2. Linux计划任务

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring

上一篇:如何使用Bash Shell

下一篇:如何实现Shell脚本基于SVN的代码提交量统计工具

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》