每 10 分钟调用一次函数

2022-09-01 12:38:07

我不是专家,只是初学者。所以我恳请你为我写一些代码。

如果我有两个类,并且 ,并且里面有一个名为 .我想从每十分钟调用一次这个函数。CLASS ACLASS BCLASS Bfunb()CLASS A

你已经给了我一些想法,但我不太明白。

你能发布一些示例代码吗?


答案 1

看看 ScheduledExecutorService

下面是一个具有方法的类,该方法将 ScheduledExecutorService 设置为每十秒发出一次哔哔声,持续一小时:

 import static java.util.concurrent.TimeUnit.*;
 class BeeperControl {
    private final ScheduledExecutorService scheduler =
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
                public void run() { System.out.println("beep"); }
            };
        final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
    }
 }

答案 2
import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

public class ClassExecutingTask {

    long delay = 10 * 1000; // delay in milliseconds
    LoopTask task = new LoopTask();
    Timer timer = new Timer("TaskName");

    public void start() {
        timer.cancel();
        timer = new Timer("TaskName");
        Date executionDate = new Date(); // no params = now
        timer.scheduleAtFixedRate(task, executionDate, delay);
    }

    private class LoopTask extends TimerTask {
        public void run() {
            System.out.println("This message will print every 10 seconds.");
        }
    }

    public static void main(String[] args) {
        ClassExecutingTask executingTask = new ClassExecutingTask();
        executingTask.start();
    }


}

推荐