Java实现定时任务

1、Timer

JDK自带的Timer API算是最古老的定时任务实现方式了。Timer是一种定时器工具,使用java.util.Timer工具类。用来在一个后台线程计划执行指定任务。它可以安排任务“执行一次”或者定期“执行多次”。

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

/**
 * Timer是JAVA自带的定时任务类;优点:使用方便
 */
public class MyTimerTask {
    public static void main(String[] args) {
        // 定义一个定时任务
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
                String dateStr = sdf.format(new Date());
                System.out.println("运行定时任务:" + dateStr);
            }
        };
 
        // 计时器
        Timer timer = new Timer();
        // 添加执行任务(延迟 1s 执行,每 3s 执行一次)
        timer.schedule(timerTask, 1000, 3000);
    }
}

2、基于@Scheduled注解

2.1、SpringBoot启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(value = "com.example.schedule.schedule")
public class DemoApplication {

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

}

2.2、实现示例

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

/**
 * @Description:
 * @Author: yangyongbing
 * @CreateTime: 2023/07/27  16:58
 * @Version: 1.0
 */

@EnableScheduling
@Configuration
public class ScheduleTask {

    @Scheduled(cron = "0/5 * * * * ?")
    private void taskOne(){
        System.out.println("------------------------------------------*********************taskOne***************************------------------------------------------------------------");
    }

    @Scheduled(cron = "0/3 * * * * ?")
    private void taskTwo(){
        System.out.println("------------------------------------------*********************taskTwo***************************------------------------------------------------------------");
    }
}

注解含义:

 * @Scheduled(cron = "0/5 * * * * ?") //每隔5s执行一次
 * @Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行
 * @Scheduled(fixedDelayString = "5000") //上一次执行完毕时间点之后5秒再执行
 * @Scheduled(fixedRate = 5000) //上一次开始执行时间点之后5秒再执行
 * @Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值