每小时运行一次Java代码 [英] Run Java code once every hour

查看:51
本文介绍了每小时运行一次Java代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的Java程序,该功能在分针为20时每小时运行一些代码.问题在于,我的操作方式非常占用CPU资源.我对Quartz很熟悉,但是我正在寻找更简单的解决方案,有什么想法吗?

I'm tryng to write a simple Java program that runs some code every hour when the minute hand is at 20. The issue is that that the way I'm doing it is incredibly CPU intensive. I'm familiar with Quartz but I'm looking for a much simpler solution, any ideas?

    boolean run = true;
    while(run){
        Calendar calendar = new GregorianCalendar();
        int minute = calendar.get(Calendar.MINUTE);
        if(minute == 20){
            //Do some Stuff             
        }
    }

推荐答案

一个简单的解决方案是使用Executors框架:

A simple solution is to use the Executors framework:

final ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();
s.scheduleAtFixedRate(task, secondsToFirstOccurence, 60*60, TimeUnit.SECONDS);

并使用一些逻辑找出 secondsToFirstOccurence .这可能涉及一个 Calendar 实例,但使用JodaTime会更加方便.

And use some logic to find out secondsToFirstOccurence. This will probably involve a Calendar instance, but would be much more convenient with JodaTime.

这篇关于每小时运行一次Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆