java - Java定时调用方法

标签 java

如何在特定时间调用方法?

例如在6:00和13:00调用方法。

我正在为 Windows 桌面应用程序工作。

最佳答案

看看 TimerTimerTask类。您可以安排线程在特定时间或重复执行。

public class Alarm {
    Timer _timer;

    public Alarm() {

        // Create a Date corresponding to 10:30:00 AM today.
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 10);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);

        Date alarmTime = calendar.getTime();

        _timer = new Timer();
        _timer.schedule(new AlarmTask(), alarmTime);
    }

    class AlarmTask extends TimerTask {
        /**
         * Called on a background thread by Timer
         */
        public void run() {
            // Do your work here; it's 10:30 AM!

            // If you don't want the alarm to go off again
            // tomorrow (etc), cancel the timer
            timer.cancel();
        }
    }
}

关于java - Java定时调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2331736/

相关文章:

java - Hibernate:根据实体类自动创建/更新数据库表

java - 如何在 SimpleXML (Java) 中将 InputNode 获取为字符串

java - 在 Hibernate 中存储坐标 (x,y) 的首选方式是什么?

java - 使用 JavaFX 内容部署 Swing 应用程序

java - 检测类文件时出错 (asm.ClassWriter.getCommonSuperClass)

java - 将 HTTP DELETE 请求实体主体映射到方法参数

java - 在类 'location' 中找不到属性 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer' 的 setter

java - 将 Rest 服务添加到 Struts 应用程序

java - 如何发布java应用程序?

JavaFX TabPane : How to listen to selection changes