定时任务的回归

Timer任务

package com.example.express.task;

import java.util.Timer;

public class TimerTaskUse {

    public static void main(String[] args) {
        Timer timer = new Timer();
        JDKTimeTask jdkTimeTask = new JDKTimeTask();

        // timer.schedule(jdkTimeTask,1000L); //在指定延迟时间后执行指定的任务

        timer.schedule(jdkTimeTask,5000L,1000L);//等待5秒开始执行任务,固定循环执行为1秒。

    }
}

package com.example.express.task;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * JDK自带定时器工具Time
 * TimerTask 如果抛出了未检出的异常,那么整个Timer线程都会失败,后面的任务也不再调度执行
 */
public class JDKTimeTask extends TimerTask {

    @Override
    public void run() {
        //要执行的任务
        System.out.println(LocalDateTime.now()+" 线程id:"+Thread.currentThread().getId()+" 线程名:"+Thread.currentThread().getName() );
    }
}

Scheduler任务

package com.example.express.task;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;


/**
 * @author 简水君
 *
 * 这里异步执行调度任务
 * 1.需要配置线程池参数
 * 2.开启异步支持(在启动类或配置类上添加`@EnableAsync`)
 * 3.在定时任务方法上添加`@Async`。
 */
@Configuration
//@EnableScheduling//开启任务调度(要么在启动类开启,要么在配置类开启,哪一个都行)
@EnableAsync//开启异步支持
public class SchedulerConfig {

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(50);
        taskScheduler.setThreadNamePrefix("async-task-"); // 线程名前缀
        taskScheduler.setAwaitTerminationSeconds(60); // 等待终止秒数
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true); // 关闭时等待任务完成
        return taskScheduler;
    }
}

package com.example.express.task;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class AsyncCornTaskJob {


    private volatile int count = 30;

    @Async//开启异步
    @Scheduled(cron = "* * * * * ?")
    public void task() {
        if (count > 0) {
            int current = count;
            // 模拟业务处理时间
            try {
                Thread.sleep(new Random().nextInt(50));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count = current - 1;

            System.out.println(Thread.currentThread().getName() + "正在卖第 " + current + "票,还剩" + (count) + "张票");
        }else {
            System.out.println("票已卖完");
        }

    }

}

posted @ 2025-06-04 10:55  加油酱  阅读(6)  评论(0)    收藏  举报