Run java function every hour

前端 未结 4 776
孤街浪徒
孤街浪徒 2020-12-19 09:02

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

4条回答
  •  独厮守ぢ
    2020-12-19 09:53

    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.

提交回复
热议问题