2

Currently working on an algorithm for something and I need to run code at the same time every day. I've tried creating a timer but I'm not really familiar with it and the most I was able to do was run code every x seconds. I know I could do every 86400 seconds but that seems like a janky solution at best and I feel like there is a better solution. Please let me know if you have any ideas. Much appreciated.

Meefy 777
  • 21
  • 1
  • If converting to seconds or millliseconds is your only issue, use [TimeUnit](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/concurrent/TimeUnit.html).DAYS.toMillis(1) or [Duration](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/time/Duration.html).ofDays(1).toMillis() – VGR Feb 26 '21 at 14:51
  • Does it have to be in Java? Why not use cron (if you're on Linux) or Task Scheduler (if you're on Windows)? – k314159 Feb 26 '21 at 14:56
  • You can use cronJobs to schedule jobs for a defined time. refer to this link https://stackoverflow.com/questions/22163662/how-to-create-a-java-cron-job – Tarun Dadlani Feb 26 '21 at 14:58
  • Solution of same question follow link: [Scheduler's details][1] [1]: https://stackoverflow.com/questions/7814089/how-to-schedule-a-periodic-task-in-java – Jimmy Feb 26 '21 at 15:27

2 Answers2

-1

Say if you want to run yourTask() at specific time (say 10:00), you could do as below:

Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 10);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);

Timer timer = new Timer();
timer.schedule(yourTask(), today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
  • this doens't compile, you'd need to pass a `TimerTask` reference to `schedule()` but currently you're executing `yourTask()` directly – Lino Feb 26 '21 at 14:56
  • `Calendar` class was years ago supplanted by the *java.time* classes defined in JSR 310. `Timer` was years ago supplanted by `ScheduledExecutorService`. – Basil Bourque Feb 26 '21 at 16:21
  • This works fine! Thanks so much. The comment above is correct yourTask() didn't work, I just defined the run() method in scheduler and it worked fine. – Meefy 777 Feb 27 '21 at 14:28
-2

There are different shedulers you can use. Quartz is one of them for example

premek.v
  • 231
  • 4
  • 14