Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java update scheduler

作者:若此生已赞。   发布日期:2025-10-13   浏览:83

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();
    }
}

解释说明

  1. JavaUpdateScheduler 类:

    • 使用 TimerTimerTask 来实现定时任务调度。
    • 构造函数初始化 Timer 对象。
  2. scheduleAtFixedRate 方法:

    • 接受一个 TimerTask 实例、初始延迟时间和执行间隔时间作为参数。
    • 调用 timer.scheduleAtFixedRate 方法来安排任务在固定的时间间隔内重复执行。
  3. stop 方法:

    • 停止调度器并取消所有已安排的任务。
  4. main 方法:

    • 创建 JavaUpdateScheduler 实例。
    • 定义一个示例任务 updateTask,它会在每次执行时打印一条消息。
    • 安排该任务每 10 秒执行一次,并在 5 秒后首次执行。
    • 启动一个新的线程,在 60 秒后停止调度器。

上一篇:java中循环语句有哪些

下一篇:java imageio

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站