Spring boot 定时器及其他定时器扩展

本文详细介绍了SpringBoot中实现定时任务的多种方式,包括使用@Schedule注解、Timer类、ScheduledExecutorService等,并提供了具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.关于spring boot定时任务,其实就是两个注解:
(1.)@EnableScheduling:定时任务的启动注解,标注在application启动类上。在 Spring Boot 的配置类中,标注上这个注解,就可以对项目中的方法某些方法使用@Schedule注解,将其变为定时自动执行。

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * The type Spring boot demo application.
 *
 * @author lxp
 * @date 2019 -07-30 16:35:15
 */
@EnableScheduling
@SpringBootApplication
public class SpringBootDemoApplication {

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

}

(2.)@Schedule:
这里用到了定时表达式cron,代表一分钟一次;
另外@Scheduled(fixedRate = 5000) 注解来定义每过5秒执行的任务;
@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行;
@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行;
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次

package com.example.Job;


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 定时
 *
 * @author lxp
 * @date 2019 -07-17 09:26:56
 */
@Component
@Slf4j
public class ScheduleTask {

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

    @Scheduled(cron = "0 0/1 * * * ?")
    public void getTime() throws Exception {
        log.info("loginIntNational定时任务启动");
        log.info(String.valueOf(dateTime.format(new Date())));
    }
}

注意:
记得加上@Component,这个注解作用是注入到spring容器进行管理。
或者@Repository这个注解也是可用的,这个注解作用会被作为持久层操作的bean来使用,这两个注解部分功能是一样的。

2.Timer类定时:

package com.example;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2019/8/7.
 */
public class TimeTest {
    public static void main(String[] args) throws Exception {
            // 第一个参数是任务,第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间,时间单位是毫秒
            new Timer().scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("定时任务开始:" + new Date().toString());
                }
            },0L,1000L);
        }
}

3.java.util.concurrent.ScheduledExecutorService定时:

package com.example;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2019/8/7.
 */
public class ScheduledExecutorServiceTest{
    public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    // task to run goes here  
                    System.out.println("定时任务开始:"+ new Date().toString());
                }
            };
            ScheduledExecutorService service = Executors
            .newSingleThreadScheduledExecutor();
            // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间(单位s)
            service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS);
    }
}

4.java.lang.Thread定时:

package com.example;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2019/8/7.
 */
public class ThreadTest {
    public static void main(String[] args) throws Exception {
        Runnable runnable = () -> {
            while (true) {

                System.out.println("定时任务开始:" + new Date().toString());

                try {
                    //时间间隔,单位是毫秒
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
        }
}

5.java.util.concurrent.ScheduledThreadPoolExecutor + org.apache.commons.lang3.concurrent.BasicThreadFactory定时:
需要导入的jar:

<dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-lang3</artifactId>
         <version>3.6</version>
     </dependency>
package com.example;


import java.util.Date;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


import org.apache.commons.lang3.concurrent.BasicThreadFactory;

/**
 * Created by Administrator on 2019/7/18.
 */
public class ScheduledThreadPoolExecutorTest {

        public static void main(String[] args) {
            ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(
                    1, new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(false).build());
            // 第一个参数是任务,第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间,第四个参数是时间单位
            scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> System.out.println("定时任务开始:" + new Date().toString()), 0L, 1L, TimeUnit.SECONDS);
        }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸟驿站ㅤ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值