如何只运行30分钟的java函数

发布于 2024-09-25 07:34:25 字数 124 浏览 0 评论 0 原文

我需要创建一个仅运行 30 分钟的 java 函数,并在 30 分钟结束时执行一些操作。但如果满足正确的条件,它也应该能够在给定时间之前自行终止。我不希望该函数处于休眠状态,因为它应该收集数据,因此没有休眠线程。

谢谢

I need to create a java function that will only run for 30 minutes, and at the end of the 30 minutes it executes something. But it should also be able to self terminate before the given time if the right conditions are met. I don't want the function to be sleeping as it should be collecting data, so no sleeping threads.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

灯下孤影 2024-10-02 07:34:25

使用: Timer.schedule(TimerTask, long )

public void someFunctino() {
    // set the timeout    
    // this will stop this function in 30 minutes
    long in30Minutes = 30 * 60 * 1000;
    Timer timer = new Timer();
    timer.schedule( new TimerTask(){
          public void run() {
               if( conditionsAreMet() ) { 
                   System.exit(0);
                }
           }
     },  in30Minutes );

     // do the work... 
      .... work for n time, it would be stoped in 30 minutes at most
      ... code code code
}

Use: Timer.schedule( TimerTask, long )

public void someFunctino() {
    // set the timeout    
    // this will stop this function in 30 minutes
    long in30Minutes = 30 * 60 * 1000;
    Timer timer = new Timer();
    timer.schedule( new TimerTask(){
          public void run() {
               if( conditionsAreMet() ) { 
                   System.exit(0);
                }
           }
     },  in30Minutes );

     // do the work... 
      .... work for n time, it would be stoped in 30 minutes at most
      ... code code code
}
伴我心暖 2024-10-02 07:34:25

使用 System.currentTimeMillis() 获取开始时间,计算停止时间,并在收集想要收集的数据时不时检查当前时间。另一种方法是将计时器和数据收集解耦,以便它们每个都可以在自己的线程中运行。

对于更具体的答案,如果您能告诉您正在收集什么数据以及您如何收集这些数据,将会很有帮助。

Get the start time with System.currentTimeMillis(), calculate the time when to stop and check the current time every now and then while you're collecting the data you want to collect. Another way would be to decouple the timer and the data collecting, so that each of them could run in their own threads.

For a more specific answer, it would be helpful if you would tell what data you are collecting and how you are collecting it.

情话已封尘 2024-10-02 07:34:25

像这样的事情会起作用:

long startTime = System.currentTimeMillis();
long maxDurationInMilliseconds = 30 * 60 * 1000;

while (System.currentTimeMillis() < startTime + maxDurationInMilliseconds) {
    // carry on running - 30 minutes hasn't elapsed yet

    if (someOtherConditionIsMet) {
        // stop running early
        break;
    }
}

Something like this will work:

long startTime = System.currentTimeMillis();
long maxDurationInMilliseconds = 30 * 60 * 1000;

while (System.currentTimeMillis() < startTime + maxDurationInMilliseconds) {
    // carry on running - 30 minutes hasn't elapsed yet

    if (someOtherConditionIsMet) {
        // stop running early
        break;
    }
}
全部不再 2024-10-02 07:34:25

现代 java.util.concurrent 方式将使用 ExecutorService。有多个invoke 方法会超时。

这是一个启动示例:

public static void main(String args[]) throws Exception {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.invokeAll(Arrays.asList(new Task()), 30, TimeUnit.MINUTES);
    executor.shutdown();
}

其中 Task 如下所示:

public class Task implements Callable<String> {

    @Override
    public String call() {
        // Just a dummy long running task.
        BigInteger i = new BigInteger("0");
        for (long l = 0; l < Long.MAX_VALUE; l++) {
            i.multiply(new BigInteger(String.valueOf(l)));

            // You need to check this regularly..
            if (Thread.interrupted()) {
                System.out.println("Task interrupted!");
                break; // ..and stop the task whenever Thread is interrupted.
            }
        }
        return null; // Or whatever you'd like to use as return value.
    }

}

另请参阅:

The modern java.util.concurrent way would be using ExecutorService. There are several invoke methods taking a timeout.

Here's a kickoff example:

public static void main(String args[]) throws Exception {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.invokeAll(Arrays.asList(new Task()), 30, TimeUnit.MINUTES);
    executor.shutdown();
}

where Task look like this:

public class Task implements Callable<String> {

    @Override
    public String call() {
        // Just a dummy long running task.
        BigInteger i = new BigInteger("0");
        for (long l = 0; l < Long.MAX_VALUE; l++) {
            i.multiply(new BigInteger(String.valueOf(l)));

            // You need to check this regularly..
            if (Thread.interrupted()) {
                System.out.println("Task interrupted!");
                break; // ..and stop the task whenever Thread is interrupted.
            }
        }
        return null; // Or whatever you'd like to use as return value.
    }

}

See also:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文