使用spring boot 创建一个简单的定时任务

2019-10-30  本文已影响0人  孑鼠

首先创建一个springboot项目

使用springboot用quzrtz

第一步

在pom文件中导入spring boot集合quzrtz的框架的maven的坐标

      <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-quartz</artifactId>

        </dependency>

导入依赖之后我们就可以使用定时任务了(简单的使用)

package com.example.demo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication

@EnableScheduling      //开启任务调度功能

public class DemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);

    }

}

在spring boot的启动类添加注解

@EnableScheduling

是告诉spring 开启了任务调度的框架

然后我们在再书写一个任务的实体类

package com.example.demo.Scheduled;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

import java.util.Date;

@Component

public class PrintCurrentTimeTask {

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

    @Scheduled(cron = "0/5 * * * * ? ")    //每5秒打印当前时间

    public void printCurrentTime() {

        System.out.println("Current Time is:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

    }

    @Scheduled(fixedRate = 3000)

    public void test(){

        System.out.println("当前时间为:"+dataFormat.format(new Date()));

    }

}

@Component是说明将这个类交给spring管理

cron的表达式被用来配置CronTrigger实例。 cron的表达式是字符串,实际上是由七子表达式,描述个别细节的时间表。这些子表达式是分开的空白,代表:

@Scheduled(cron = "0/5 * * * * ? "

1.        Seconds

2.        Minutes

3.        Hours

4.        Day-of-Month

5.        Month

6.        Day-of-Week

7.        Year (可选字段)

例  "0 0 12 ? * WED" 在每星期三下午12:00 执行,

然后当spring boot启动的时候他会将这个类交给spring管理,并会直接里面的任务

上一篇 下一篇

猜你喜欢

热点阅读