Run java function every hour

给你一囗甜甜゛ 提交于 2019-11-28 12:30:22
Jean Logeart

Use a ScheduledExecutorService:

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        sendScreenShot();
    }
}, 0, 1, TimeUnit.HOURS);

Prefer using a ScheduledExecutorService over Timer: Java Timer vs ExecutorService?

According to this article by Oracle, it's also possible to use the @Schedule annotation:

@Schedule(hour = "*")
public void doSomething() {
    System.out.println("hello world");
}

For example, seconds and minutes can have values 0-59, hours 0-23, months 1-12.

Further options are also described there.

java's Timer works fine here.

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

Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
    public void run() {
        // ...
    }
}, delay, 1 * 3600 * 1000); // 1 hour between calls

For this type of period execution, meaning every day or every hour, all you need is using a Timer like this :

public static void main(String[] args) throws InterruptedException {
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 7);
        today.set(Calendar.MINUTE, 45);
        today.set(Calendar.SECOND, 0);

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("I am the timer");
            }
        };
//        timer.schedule(task, today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); // period: 1 day
        timer.schedule(task, today.getTime(), TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); // period: 5 seconds

    }

this exemple will execute the timetask every 5 seconds from the current date and 7:45 am. Good Luck.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!