我需要在 Java 中睡很长时间(几天)

发布于 2024-08-01 20:12:42 字数 140 浏览 7 评论 0原文

我有一个应用程序需要按计划做一件事,而且只做一件事,并且它能够轻松计算出下次需要运行的时间。 从现在开始,它可能不需要在几天或几个月内运行此任务,但可能每隔几毫秒就会在其他方面处于活动状态。

我正在寻找一种简单的轻量级方法来安排该任务的运行。

I have an app that needs to do one thing, and one thing only, on a schedule and it will be able to calculate easily the time it next needs to run. It may not need to run this task for days or months from now, but will probably be active in every other respect every few milliseconds.

I'm looking for a simple lightweight approach to scheduling that one task to run.

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

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

发布评论

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

评论(6

明天过后 2024-08-08 20:12:42

在 Unix 上,查看系统工具 cronat

在 Windows 上,系统设置中有一个作业计划程序。

对于简单的仅 Java 解决方案,请尝试 定时器API

对于更复杂的纯 Java 解决方案,请查看 quartz

On Unix, have a look at the system tools cron or at.

On Windows, there is a job scheduler in the system settings.

For a simple Java-only solution, try the Timer API.

For a more complex Java-only solution, have a look at quartz.

标点 2024-08-08 20:12:42

如果您的 Java 应用程序打算连续运行,那么您可以使用 Timer< /a> 安排执行的类

如果您的应用程序不会连续运行,那么其他答案是正确的。 cron / 任务调度程序是可行的方法。

If your java app is intended to be running continuously then you can use the Timer class to schedule execution

If your app isn't going to be running continuously then the other answers are correct. cron / task scheduler are the way to go.

时光匆匆的小流年 2024-08-08 20:12:42

那么,如果您需要应用程序在特定时间运行,您可以安排 cron 作业。 或者,您可以编写一个简单的类,它将自行安排特定的时间。 由于我不知道那里有任何图书馆(从来没有真正需要寻找一个),所以我很久以前就写了一堂课来为自己安排任务。 希望它能有所帮助,大致上:

import java.util.*;

public abstract class TimeMonitor extends Thread
    {
        protected double execution_time;
        protected boolean execute_at_startup;

        public TimeMonitor()
            {
                execute_at_startup = false;
            }

        public TimeMonitor(double time)
            {
                execution_time = time;
                execute_at_startup = false;
            }

        public void startTimer()
            {
                setPriority(Thread.MIN_PRIORITY);
                start();
            }

        public void setTime(double time)
            {
                execution_time = time;
            }

        public void executeAtStartup()
            {
                execute_at_startup = true;
            }

        public void run()
            {
                if (execute_at_startup)
                    doTimedAction();

                while (true)
                    {
                        long runtime = (long)(execution_time * 3600 * 1000);
                        long now     = getTime();
                        long sleep   = 0;

                        // Calculate how long to way until first run
                        if (runtime > now)
                            sleep = runtime - now;
                        else
                            sleep = 24 * 3600 * 1000 - now + runtime;

                        try
                            {
                                Thread.sleep(sleep);
                            }
                        catch (InterruptedException e)
                            {
                                logError("Wait thread has been interrupted.", e);
                                continue;
                            }

                        doTimedAction();
                    }
            }

        /**
         * Calculates number of milliseconds from start of the day.
         *
         * @return Number of milliseconds.
         */
        private long getTime()
            {
                Calendar cal = Calendar.getInstance();
                int hours   = cal.get(Calendar.HOUR_OF_DAY);
                int minutes = cal.get(Calendar.MINUTE);
                int seconds = cal.get(Calendar.SECOND);
                int millis  = cal.get(Calendar.MILLISECOND);

                return (hours * 3600 + minutes * 60 + seconds) * 1000 + millis;
            }

        private void doTimedAction()
            {
                try
                    {
                        performAction();
                    }
                catch (Throwable e)
                    {
                        logError("An error occured during timed execution.", e);
                    }
            }

        /**
         * This method will be called when an error or a warning occures.
         *
         * @param msg
         * @param e
         */
        protected void logError(String msg, Throwable e)
            {
                System.out.println(msg);
                e.printStackTrace();
            }

        /**
         * Action to be performed when scheduled time happens.
         */
        protected abstract void performAction();
    }

像这样扩展使用它:

        TimeMonitor archiver = new TimeMonitor()
            {
                protected void performAction()
                    {
                        // Do the task
                    }
            };

        archiver.setTime(16.5); // Run at 4:30pm
        archiver.startTimer();

Well, you can schedule a cron job if you need your app to run at certain times. Or, you can write a simple class that will schedule itself for certain times. Since I'm not aware of any library out there (never really needed to look for one), I wrote a class long ago to schedule a task for myself. Hope it helps and in ballpark:

import java.util.*;

public abstract class TimeMonitor extends Thread
    {
        protected double execution_time;
        protected boolean execute_at_startup;

        public TimeMonitor()
            {
                execute_at_startup = false;
            }

        public TimeMonitor(double time)
            {
                execution_time = time;
                execute_at_startup = false;
            }

        public void startTimer()
            {
                setPriority(Thread.MIN_PRIORITY);
                start();
            }

        public void setTime(double time)
            {
                execution_time = time;
            }

        public void executeAtStartup()
            {
                execute_at_startup = true;
            }

        public void run()
            {
                if (execute_at_startup)
                    doTimedAction();

                while (true)
                    {
                        long runtime = (long)(execution_time * 3600 * 1000);
                        long now     = getTime();
                        long sleep   = 0;

                        // Calculate how long to way until first run
                        if (runtime > now)
                            sleep = runtime - now;
                        else
                            sleep = 24 * 3600 * 1000 - now + runtime;

                        try
                            {
                                Thread.sleep(sleep);
                            }
                        catch (InterruptedException e)
                            {
                                logError("Wait thread has been interrupted.", e);
                                continue;
                            }

                        doTimedAction();
                    }
            }

        /**
         * Calculates number of milliseconds from start of the day.
         *
         * @return Number of milliseconds.
         */
        private long getTime()
            {
                Calendar cal = Calendar.getInstance();
                int hours   = cal.get(Calendar.HOUR_OF_DAY);
                int minutes = cal.get(Calendar.MINUTE);
                int seconds = cal.get(Calendar.SECOND);
                int millis  = cal.get(Calendar.MILLISECOND);

                return (hours * 3600 + minutes * 60 + seconds) * 1000 + millis;
            }

        private void doTimedAction()
            {
                try
                    {
                        performAction();
                    }
                catch (Throwable e)
                    {
                        logError("An error occured during timed execution.", e);
                    }
            }

        /**
         * This method will be called when an error or a warning occures.
         *
         * @param msg
         * @param e
         */
        protected void logError(String msg, Throwable e)
            {
                System.out.println(msg);
                e.printStackTrace();
            }

        /**
         * Action to be performed when scheduled time happens.
         */
        protected abstract void performAction();
    }

Extend to use it like so:

        TimeMonitor archiver = new TimeMonitor()
            {
                protected void performAction()
                    {
                        // Do the task
                    }
            };

        archiver.setTime(16.5); // Run at 4:30pm
        archiver.startTimer();
兮颜 2024-08-08 20:12:42

Quartz is good for this type of thing. It's supported well in Spring apps as well.

你的笑 2024-08-08 20:12:42

编写 Windows 服务(或 Linux 系统的守护程序)


以下是一些帮助您入门的链接:

屌丝范 2024-08-08 20:12:42

只需使用java.util.concurrent,它有一个计划执行小部件。 您需要添加一个保护条件以防止过度运行,或者在当前执行的末尾添加下一个执行。

Just use java.util.concurrent, it has a scheduled execution widget. You'd need to add a guard condition to prevent excessive runs, or else add the next execution at the end of the current one.

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