import java.util.Timer;
import java.util.TimerTask;
public class JavaUpdateScheduler {
private Timer timer;
public JavaUpdateScheduler() {
timer = new Timer();
}
/**
* Schedules a task to run at fixed intervals.
*
* @param task The task to be scheduled.
* @param delay Initial delay in milliseconds before the first execution.
* @param interval Interval between successive executions in milliseconds.
*/
public void scheduleAtFixedRate(TimerTask task, long delay, long interval) {
timer.scheduleAtFixedRate(task, delay, interval);
}
/**
* Stops the scheduler and cancels all scheduled tasks.
*/
public void stop() {
timer.cancel();
}
public static void main(String[] args) {
JavaUpdateScheduler scheduler = new JavaUpdateScheduler();
// Example task to be scheduled
TimerTask updateTask = new TimerTask() {
@Override
public void run() {
System.out.println("Executing update task...");
// Add your update logic here
}
};
// Schedule the task to run every 10 seconds with an initial delay of 5 seconds
scheduler.scheduleAtFixedRate(updateTask, 5000, 10000);
// Stop the scheduler after 60 seconds
new Thread(() -> {
try {
Thread.sleep(60000);
scheduler.stop();
System.out.println("Scheduler stopped.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
JavaUpdateScheduler 类:
Timer
和 TimerTask
来实现定时任务调度。Timer
对象。scheduleAtFixedRate 方法:
TimerTask
实例、初始延迟时间和执行间隔时间作为参数。timer.scheduleAtFixedRate
方法来安排任务在固定的时间间隔内重复执行。stop 方法:
main 方法:
JavaUpdateScheduler
实例。updateTask
,它会在每次执行时打印一条消息。上一篇:java中循环语句有哪些
下一篇:java imageio
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站