• spring计划任务


    Spring4.x高级话题(三):计划任务Schedule

    . 点睛

    从Spring3.1开始,计划任务在Spring中的实现变得异常的简单。首先通过在配置类注解@EnableScheduling来开启计划任务的支持,然后在要执行计划任务的方法上注解@Scheduled来声明这是一个计划任务。

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

    . 示例

    1. 计划任务执行类

    package org.light4j.sping4.senior.taskscheduler;

     

    import java.text.SimpleDateFormat;

    import java.util.Date;

     

    import org.springframework.scheduling.annotation.Scheduled;

    import org.springframework.stereotype.Service;

     

    @Service

    public class ScheduledTaskService {

     

          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 28 11 ? * *"  ) //②

          public void fixTimeExecution(){

              System.out.println("在指定时间 " + dateFormat.format(new Date())+"执行");

          }

    }

    代码解释:

    ① 通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行。
    ② 使用cron属性可按照指定时间执行,本例指的是每天11点28分执行;cron是UNIX和类UNIX(Linux)系统下的定时任务。

    2. 配置类

    package org.light4j.sping4.senior.taskscheduler;

     

    import org.springframework.context.annotation.ComponentScan;

    import org.springframework.context.annotation.Configuration;

    import org.springframework.scheduling.annotation.EnableScheduling;

     

    @Configuration

    @ComponentScan("org.light4j.sping4.senior.taskscheduler")

    @EnableScheduling //①

    public class TaskSchedulerConfig {

     

    }

    代码解释:

    ① 通过@EnableScheduling注解开启对计划任务的支持。

    3. 运行

    package org.light4j.sping4.senior.taskscheduler;

     

    import org.springframework.context.annotation.AnnotationConfigApplicationContext;

     

    public class Main {

        public static void main(String[] args) {

             AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);

        }

    }

    运行结果如下图所示:

    4. 源代码示例:

    github地址:点击查看

  • 相关阅读:
    Django Rest Framework 视图和路由
    DRF 权限 频率
    DRF 版本 认证
    Serializers 序列化组件
    学DRF之前
    RESTful
    windows下vmware配置nat网络
    python之路——网络编程
    图片上传
    数据库基本设计规范:
  • 原文地址:https://www.cnblogs.com/wangchaonan/p/10731513.html
Copyright © 2020-2023  润新知