Several Methods of Implementing Timer in Java

Table of contents

Method 1: Using the Timer and TimerTask classes

Method 2: Use a thread pool

Method 3: Use Spring Task

Method 4: Through the quartz task scheduling tool


There are many ways to implement timers in Java. This chapter mainly talks about several known methods:

Method 1: Using the Timer and TimerTask classes

1. Timer and TimerTask are classes under the java.util package, used to implement timing tasks

Step 1: Create a TimerTask timer task, which can be created through an anonymous inner class

Step 2: Create a Timer timer, call the timer method to execute the timer task

2. The two methods schedule() and scheduleAtFixedRate() of Timer and their overloaded methods:

void schedule(TimerTask task, long delay): Execute a task after a specified time, where delay represents the delay in milliseconds, if it is set to 1000, it means that a timer task will be executed after 1 second;

void schedule(TimerTask task, long delay, long period): Periodically execute the task after specifying the delay for the specified time (after delay milliseconds, execute every period milliseconds)

void scheduleAtFixedRate(TimerTask task, long delay, long period): Periodically execute the task after specifying the specified time delay (after delay milliseconds, execute every period milliseconds)

void scheduleAtFixedRate(TimerTask task, Date firstTime,long period) : Starting from the specified date firstTime, execute the task every period milliseconds

3. Case code

public class TimerExample {
    public static void main(String[] args) {
        // 创建定时器
        Timer timer = new Timer();
        // 创建定时器任务
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Hello world!");
            }
        };

        timer.schedule(timerTask, 1000); // 1秒后执行一次
        timer.schedule(timerTask, 2000, 2000); // 两秒后每两秒执行一次
        timer.scheduleAtFixedRate(timerTask, 3000, 3000); // 3秒后每3秒执行一次
        timer.scheduleAtFixedRate(task, new Date(), 4000); // 每4秒执行一次
    }

}

Method 2: Use a thread pool

The method of the thread pool is the same as Timer. TimeUnit is an enumeration type used to specify the time unit, including NANOSECONDS (nanoseconds), MICROSECONDS (microseconds), MILISECONDS (milliseconds), SECONDS (seconds), MINUTE (minutes) , HOURS (hours) and DAYS (days).

Case code:

public class TimerExample {
    public static void main(String[] args) {
        // 创建定时器任务
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Hello world!");
            }
        };

        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);

        scheduledThreadPool.schedule(timerTask, 1000, TimeUnit.MILLISECONDS);
        scheduledThreadPool.scheduleAtFixedRate(timerTask, 1000, 1000, TimeUnit.MILLISECONDS);
    }

}

Method 3: Use Spring Task

Step 1: Add the @EnableScheduling annotation to the springBoot startup class

@EnableScheduling
@SpringBootApplication
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

}

Step 2: Create a bean of a scheduled task class, use the @Schedule annotation on the method of the class, and set the properties of the timer through the cron attribute of the annotation

@Component
public class TimerTask {
    @Scheduled(cron = "0 7 2 26 7 *")
    public void task() {
        System.out.println("定时任务...");
    }

}

The above code specifies to execute a timed task at 02:07:00 on July 26, 2022. If you are interested in cron expressions, you can learn about them, so I won’t introduce them here.

Method 4: Through the Quartz task scheduling tool

Step 1: Add quartz dependency in pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

Step 2: Create a configuration class for quartz

@Configuration
public class QuartzConfig {
    // 创建一个JobDetail(工作详情)类对象,保存到Spring容器中,这个类用于封装我们编写的job接口实现类
    @Bean
    public JobDetail jobDetail(){
        System.out.println("showTime方法运行");
        return JobBuilder.newJob(QuartzJob.class)   // 绑定要运行的任务类的类对象
                .withIdentity("job")               // 设置job的名称
                .storeDurably()                     // 信息持久
                // 设置storeDurably之后,当没有触发器指向这个JobDetail时,JobDetail也不会从
                // Spring容器中删除,如果不设置这行,就会自动从Spring容器中删除
                .build();
    }

    // 声明触发器,触发器决定我们的工作\任务何时触发
    @Bean
    public Trigger trigger(){
        System.out.println("showTime触发器运行");

        // 定义Cron表达式,每分钟触发一次
        CronScheduleBuilder cronScheduleBuilder = 
                CronScheduleBuilder.cronSchedule("0/10 * * * * ?");
        
        return TriggerBuilder.newTrigger()
                .forJob(jobDetail()) // 绑定JobDetail对象
                .withIdentity("trigger") // 定义触发器名称
                .withSchedule(cronScheduleBuilder) // 绑定Cron表达式
                .build();
    }

}

Step:3: Define Job

public class QuartzJob implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        // 输出当前时间
        System.out.println(LocalDateTime.now());
    }
}

Guess you like

Origin blog.csdn.net/heyl163_/article/details/126262983