• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

springboot 计划任务Scheduled

武飞扬头像
虾米大王
帮助3

从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
系列文章
更多 icon
同类精品
更多 icon
继续加载