How can I run a function repeatedly every week Sunday at 12:01 AM while using minimal CPU during the downtime/off time? Thread.sleep()
?
Asked
Active
Viewed 1,922 times
0

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278

user1757703
- 2,925
- 6
- 41
- 62
-
possible duplicate of [How to do an action in periodic intervals in java?](http://stackoverflow.com/questions/17397259/how-to-do-an-action-in-periodic-intervals-in-java) – kosa Jul 01 '13 at 21:08
-
use cron http://stackoverflow.com/questions/7855666/cron-job-for-a-java-program – mistahenry Jul 01 '13 at 21:09
-
1Use http://www.quartz-scheduler.org/ – Amir Afghani Jul 01 '13 at 21:12
2 Answers
1
Use the @Scheduled annotation from Spring framework. The cron expression for every week Sunday at 12:01 AM is: 1 0 * * 0
@Scheduled(cron="1 0 * * 0")
public void doSomething() {
// something that execute once a week
}

Eduardo Sanchez-Ros
- 1,777
- 2
- 18
- 30
0
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
class SundayRunner implements Runnable
{
private final Runnable target;
private final ScheduledExecutorService worker;
private volatile Date now;
SundayRunner(Runnable target, ScheduledExecutorService worker) {
this.target = target;
this.worker = worker;
}
@Override
public final void run()
{
if (now == null)
now = new Date();
else
target.run();
Date next = next(now);
long delay = next.getTime() - now.getTime();
now = next;
worker.schedule(this, delay, TimeUnit.MILLISECONDS);
}
Date next(Date now)
{
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(now);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date sunday;
for (sunday = cal.getTime(); sunday.before(now); sunday = cal.getTime())
cal.add(Calendar.DATE, 7);
return sunday;
}
public static void main(String... argv)
{
ScheduledExecutorService worker =
Executors.newSingleThreadScheduledExecutor();
Runnable job = new Runnable() {
@Override
public void run()
{
System.out.printf("The time is now %tc.%n", new Date());
}
};
worker.submit(new SundayRunner(job, worker));
}
}

erickson
- 265,237
- 58
- 395
- 493