美文网首页
计划任务

计划任务

作者: MoonRiver_a1cc | 来源:发表于2019-08-18 14:31 被阅读0次

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

(1)计划任务执行类

package com.dingxin.ch3.taskscheduler;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author dingxin
 * @Date 2019/8/18 14:39
 **/
@Service
public class ScheduledTaskService {

    private static final SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000) //1
    public void reportCurrentTime(){
        System.out.println("每隔五秒执行一次 " + dateFormat.format(new Date()));
    }

    @Scheduled(cron = "0 51 14 ? * *") //2
    public void fixTimeExecutTion(){
        System.out.println("在指定时间 " + dateFormat.format(new Date()) +"执行");
    }

}

代码解释
1.通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间运行。
2.使用cron属性可按照指定时间执行,本例指的是每天14点51分执行;cron是UNIX和类UNIX(Linux)系统下的定时任务。

(2)配置类

package com.dingxin.ch3.taskscheduler;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @Author dingxin
 * @Date 2019/8/18 14:45
 **/
@Configuration
@ComponentScan("com.dingxin.ch3.taskscheduler")
@EnableScheduling //1
public class TaskSchedulerConfig {

}

代码解释
1.通过@EnableScheduling注解开启对计划任务的支持。

(3)运行

package com.dingxin.ch3.taskscheduler;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @Author dingxin
 * @Date 2019/8/18 14:47
 **/
public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);

    }
}

结果如图所示


计划任务.PNG

相关文章

  • 计划任务(定时任务)

    计划任务分为一次性计划任务与长期性计划任务。 一次性计划任务 长期性计划任务 一次性计划任务 长期性计划任务 cr...

  • Linux定时任务 day24

    1.计划任务基本概述2.计划任务时间管理3.计划任务编写实践4.计划任务如何调试 一、计划任务基本概述 1.什么是...

  • 20.Linux中的计划任务

    Linux中的计划任务At单次执行计划任务cron 计划任务的使用计划任务:在某个时段自动执行某个任务。 Linu...

  • 十二、计划任务、日志轮转

    计划任务 计划任务分为一次性和循环性的计划任务 一、一次调度执行-----at 作用: 计划任务主要是做一些周期...

  • 计划任务服务程序

    [TOC] 计划任务服务程序 计划任务分为以下两种一次性计划任务:今晚11点30分开启网站长期性计划任务:每周一的...

  • 开启计划任务

    Linux 开启计划任务 开启计划任务(指定某个文件在什么时间段启动运行) 1.开启计划任务: service c...

  • Linux计划任务crontab

    计划任务 crontab 命令的使用 设置计划任务的格式 * 表示所有时间*/n 表示...

  • 4.4 计划任务服务程序(at、crontab)(P93-95)

    计划任务服务程序(P93-95) 一、计划任务的2种分类 一次性计划任务:如,今天12:12,新建一个8.txt文...

  • day 10 网络基础配置

    计划任务网络基础配置网络基础之 TCP/IP 协议簇ssh 单次计划任务 atatdat -c ...

  • Linux如何使用crontab命令

    计划任务 定时执行 crontab -l 查看当前计划任务tail -n100 /var/log/cron 查看计...

网友评论

      本文标题:计划任务

      本文链接:https://www.haomeiwen.com/subject/hkmrsctx.html