Java 每 10 分钟调用一次函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1220975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:03:40  来源:igfitidea点击:

Calling a function every 10 minutes

javascheduling

提问by

I'm not an expert, just a beginner. So I kindly ask that you write some code for me.

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

If I have two classes, CLASS Aand CLASS B, and inside CLASS Bthere is a function called funb(). I want to call this function from CLASS Aevery ten minutes.

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

You have already given me some ideas, however I didn't quite understand.

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

Can you post some example code, please?

你可以发布一些示例代码吗?

回答by Philippe Carriere

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


}

回答by Tim

Have a look at the ScheduledExecutorService:

看看ScheduledExecutorService

Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:

这是一个带有方法的类,该类将 ScheduledExecutorService 设置为每 10 秒发出哔声一小时:

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

回答by overflow

public class datetime {

    public String CurrentDate() {

        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        String currentTime = sdf.format(dt);
        return currentTime;

    }

    public static void main(String[] args) {
        class SayHello extends TimerTask {

            datetime thisObj = new datetime();

            public void run() {
                String todaysdate = thisObj.CurrentDate();
                System.out.println(todaysdate);
            }
        }
        Timer timer = new Timer();
        timer.schedule(new SayHello(), 0, 5000); 
    }
}

回答by Fnaf Server

Try this. It will repeat the run() function every set minutes. To change the set minutes, change the MINUTES variable

尝试这个。它将每隔几分钟重复 run() 函数。要更改设置的分钟,请更改 MINUTES 变量

int MINUTES = 10; // The delay in minutes
Timer timer = new Timer();
 timer.schedule(new TimerTask() {
    @Override
    public void run() { // Function runs every MINUTES minutes.
        // Run the code you want here
        CLASSB.funcb(); // If the function you wanted was static
    }
 }, 0, 1000 * 60 * MINUTES);
    // 1000 milliseconds in a second * 60 per minute * the MINUTES variable. 

Don't forget to do the imports!

不要忘记做进口!

import java.util.Timer;
import java.util.TimerTask;

For more info, go here:

欲了解更多信息,请访问:

http://docs.oracle.com/javase/7/docs/api/java/util/Timer.htmlhttp://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

回答by byteprom

Solution with Java 8

使用 Java 8 的解决方案

ClassB b = new ClassB();    
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
    b.funb();
};
executor.scheduleWithFixedDelay(task, 0, 10, TimeUnit.MINUTES);