SpringBoot——定时任务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010837612/article/details/80354675

很多定时任务都是使用quartz实现,但是quartz使用起来相对比较复杂,今天来讲一个简单轻量的定时任务。

只要两个步骤:

入口类增加@EnableScheduling 注解:

@EnableScheduling
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

创建一个类,每秒执行test() 方法

package com.example.demo.task;

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

import java.util.Date;

@Component
public class TestTask {

    @Scheduled(fixedRate = 1000)
    public void test(){
        System.out.println((new Date()).toString());
    }
}

运行:
这里写图片描述

是不是很简单。

上面的例子只是简单的每秒执行,其实还支持cron表达式,用过linux的crontab的朋友一定不陌生。

package com.example.demo.task;

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

import java.util.Date;

@Component
public class TestTask {

    @Scheduled(cron = " */2 * * * * * ")
    public void test(){
        System.out.println((new Date()).toString());
    }
}

注意:cron表达式支持六位,不支持年

猜你喜欢

转载自blog.csdn.net/u010837612/article/details/80354675