现在的位置: 首页 > 编程语言 > 正文

SpringTaskScheduler使用实例解析

2020年02月13日 编程语言 ⁄ 共 1364字 ⁄ 字号 评论关闭

这篇文章主要介绍了Spring TaskScheduler使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

TaskScheduler

提供对计划任务提供支持; 使用@EnableScheduling开启计划任务支持 使用@Scheduled来注解计划任务的方法;

示例

演示后台间断执行任务和定时计划任务

计划任务的配置

@Configuration@EnableSchedulingpublic class DemoConfig {}

计划配置任务类

package com.wisely.task.scheduler;import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class DemoScheduledTask { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) //每五秒执行一次 public void reportCurrentTime() { System.out.println("每隔五秒执行一次 " + dateFormat.format(new Date())); } @Scheduled(cron = "0 22 11 ? * *" ) //每天上午11点22执行 public void fixTimeExecution(){ System.out.println("在指定时间 " + dateFormat.format(new Date())+"执行"); }}

测试

package com.wisely.task.scheduler;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main { @SuppressWarnings({ "unused", "resource" }) public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.wisely.task.scheduler"); }}

输出结果

每隔五秒执行一次 11:21:42每隔五秒执行一次 11:21:47每隔五秒执行一次 11:21:52每隔五秒执行一次 11:21:57在指定时间 11:22:00执行每隔五秒执行一次 11:22:02

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: Spring TaskScheduler使用实例解析

以上就上有关SpringTaskScheduler使用实例解析的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.