java 每小时运行一次java函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32228345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run java function every hour
提问by Jannik
I want to run a function every hour, to email users a hourly screenshot of their progress. I code set up to do so in a function called sendScreenshot()
我想每小时运行一次功能,向用户发送每小时进度的屏幕截图。我在一个名为 sendScreenshot() 的函数中设置了代码
How can I run this timer in the background to call the function sendScreenshot() every hour, while the rest of the program is running?
如何在后台运行此计时器以每小时调用函数 sendScreenshot(),而程序的其余部分正在运行?
Here is my code:
这是我的代码:
public int onLoop() throws Exception{
if(getLocalPlayer().getHealth() == 0){
playerHasDied();
}
return Calculations.random(200, 300);
}
public void sendScreenShot() throws Exception{
Robot robot = new Robot();
BufferedImage screenshot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
screenshotNumber = getNewestScreenshot();
fileName = new File("C:/Users/%username%/Dreambot/Screenshots/Screenshot" + screenshotNumber +".");
ImageIO.write(screenshot, "JPEG", fileName);
mail.setSubject("Your hourly progress on account " + accName);
mail.setBody("Here is your hourly progress report on account " + accName +". Progress is attached in this mail.");
mail.addAttachment(fileName.toString());
mail.setTo(reciepents);
mail.send();
}
回答by 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?
喜欢使用ScheduledExecutorService
过Timer
:
Java的定时器VS ExecutorService的?
回答by twentylemon
java's Timer
works fine here.
javaTimer
在这里工作正常。
http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html
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
回答by Edwin Lambregts
According to this article by Oracle, it's also possible to use the @Schedule
annotation:
根据Oracle 的这篇文章,也可以使用@Schedule
注释:
@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.
例如,秒和分钟的值可以是 0-59、小时 0-23、月 1-12。
Further options are also described there.
那里还描述了更多选项。
回答by Abdelhalim FELLAGUE CHEBRA
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.
这个例子将从当前日期和早上 7:45 每 5 秒执行一次时间任务。祝你好运。