Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run java function every hour

Tags:

java

schedule

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()

How can I run this timer in the background to call the function sendScreenshot() every hour, while the rest of the program is running?

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();

}
like image 904
Jannik Avatar asked Aug 26 '15 13:08

Jannik


Video Answer


2 Answers

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?

like image 91
Jean Logeart Avatar answered Oct 05 '22 05:10

Jean Logeart


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.

like image 38
Edwin Lambregts Avatar answered Oct 05 '22 05:10

Edwin Lambregts