Home > Java > javaTutorial > How to set time in java timer

How to set time in java timer

小老鼠
Release: 2023-12-26 16:31:37
Original
1615 people have browsed it

Setting method: 1. Use the run method of TimerTask to define tasks for scheduled execution; 2. Through the schedule method of Timer, you can set the start time, interval, etc. of the timer; 3. The task will be started when the program starts Execute immediately, then execute it every 1000 milliseconds, and continue execution until the timer is cancelled.

How to set time in java timer

Operating system for this tutorial: Windows 10 system, Dell G3 computer.

In Java, you can use the Timer class and TimerTask class to implement scheduled tasks. The following is a simple example that demonstrates how to use Timer and TimerTask to set a timer and execute tasks:

import java.util.Timer;
import java.util.TimerTask;
public class TimerExample {
    public static void main(String[] args) {
        // 创建定时器对象
        Timer timer = new Timer();
        // 创建定时任务对象
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // 在此处编写定时执行的任务
                System.out.println("Task executed at: " + System.currentTimeMillis());
            }
        };
        // 设置定时器,延迟0毫秒后开始执行任务,每隔1000毫秒执行一次
        timer.schedule(task, 0, 1000);
        // 等待一段时间后,取消定时任务
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 取消定时任务
        timer.cancel();
        System.out.println("Timer canceled");
    }
}
Copy after login

In the above example, the run method of TimerTask defines a task for scheduled execution. Through the schedule method of Timer, you can set the start time, interval, etc. of the timer. In this example, the task will be executed immediately after the program starts, then every 1000 milliseconds, and continue until the timer is cancelled.

Please note that the Timer class has been deprecated in Java. It is recommended to use ScheduledExecutorService to perform scheduled tasks because it provides more powerful and flexible scheduling functions. The following is an example of using ScheduledExecutorService:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorExample {
    public static void main(String[] args) {
        // 创建ScheduledExecutorService对象
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        // 创建定时任务对象
        Runnable task = () -> {
            // 在此处编写定时执行的任务
            System.out.println("Task executed at: " + System.currentTimeMillis());
        };
        // 设置定时器,延迟0毫秒后开始执行任务,每隔1000毫秒执行一次
        scheduler.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
        // 等待一段时间后,关闭定时器
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 关闭定时器
        scheduler.shutdown();
        System.out.println("Scheduler shutdown");
    }
}
Copy after login

This example uses the scheduleAtFixedRate method of ScheduledExecutorService, whose parameters include the task object, initial delay time, interval time and time unit. In this example, the task will be executed immediately after the program starts, then every 1000 milliseconds, and continue until the timer is turned off.

The above is the detailed content of How to set time in java timer. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template