Skip to content

Instantly share code, notes, and snippets.

@gturedi
Last active January 28, 2016 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gturedi/e89bc49560ec047780ad to your computer and use it in GitHub Desktop.
Save gturedi/e89bc49560ec047780ad to your computer and use it in GitHub Desktop.
simple util class to run periodic tasks on android
package gturedi.sample;
import android.content.Context;
import android.content.SharedPreferences;
public class PeriodicTask {
private static final int ONE_DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
public static void run(final Context context, Runnable runnable) {
run(context, "task", 2, runnable);
}
public static void run(final Context context, String taskName, int periodInDays, Runnable runnable) {
SharedPreferences preferences = context.getSharedPreferences(taskName, Context.MODE_PRIVATE);
long lastTime = preferences.getLong(taskName, 0);
long now = System.currentTimeMillis();
int diff = (int) ((now - lastTime) / ONE_DAY_IN_MILLIS);
if (diff >= periodInDays) {
preferences.edit().putLong(taskName, now).commit();
new Thread(runnable).start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment