Reputation: 357
I would like to execute a piece of code every 24 Hours however I'm not sure how to do this. I have some code that sets the time that I would like the cycle to start but not sure how to execute the end time
int startDay = 00; // 12am
int end = 24; // 12 pm
int hours = (end - startDay) % 24; //difference will be 24 hours
Calendar calInstanceOne = Calendar.getInstance();
// set calendar to 12 am
calInstanceOne.set(Calendar.HOUR_OF_DAY, startDay);
calInstanceOne.set(Calendar.MINUTE, 0);
calInstanceOne.set(Calendar.SECOND, 0);
calInstanceOne.set(Calendar.MILLISECOND, 0);
Do I create another Calendar instance, set to 12pm? and compare the two? Would really appreciate any insight into this.
Upvotes: 2
Views: 2556
Reputation: 4843
You may have several choices, let me outline the easiest one. The strategy is to simply use the system time to execute twenty four hours later:
package com.test;
import java.util.Calendar;
public class ExecuteCheck {
//Class fields
/* Number of milliseconds in a day
*
*/
private static final long C_DAY=24*60*60*1000;
//Object fields
/* Time last executed (or beginning of cycle), in milliseconds;
*
*/
private long lastExecuted = System.currentTimeMillis();
public ExecuteCheck() {
}
/** Set the current execution cycle time to now
*
*/
public void setExecutionTimeToNow() {
lastExecuted = System.currentTimeMillis();
}
/** Set the execution cycle time to be the value in the calendar argument.
* @param cal
*/
public void setExecutionTime(Calendar cal) {
lastExecuted = cal.getTimeInMillis();
}
/** Is it more than twenty-four hours since the last execution time?
* @return
*/
public boolean isTimeToExecute() {
return (System.currentTimeMillis() - lastExecuted) > C_DAY;
}
}
Upvotes: 0
Reputation: 4425
First store your current time then whenever app will be open compare current time with previous store time if its greater or equal 24 hour execute your code.
Upvotes: 0
Reputation: 1007276
I would like to execute a piece of code every 24 Hours
Use AlarmManager
, in conjunction with either WakefulBroadcastReceiver
or my WakefulIntentService
. Ideally, use setInexactRepeating()
on AlarmManager
for INTERVAL_DAY
, to allow Android to slide the actual time around to best save battery for the user.
Upvotes: 4
Reputation: 11244
You can use AlarmManager to make actions periodically:
Intent intent = new Intent(this, MyStartServiceReceiver.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, <24h in msecs>, pendingIntent);
Then you should register your BroadcastReceiver
in the manifest and call the method you want to execute from this receiver.
Upvotes: 4