Java – How to start a service doing something repeatedly in android

How to start a service doing something repeatedly in android… here is a solution to the problem.

How to start a service doing something repeatedly in android

Possible Duplicate:
Android regular task (cronjob equivalent)

I’m currently trying to perform a task per day following the code

public class BackupService extends Service {

private Timer timer = new Timer();
    public IBinder onBind(Intent arg0) {
         TODO Auto-generated method stub
        return null;

    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
        return START_STICKY;

private void startBackup() {

Date date = new Date(time);
        System.out.println("Backup time:" +date);
        timer.scheduleAtFixedRate(new BackupTimerTask(), date,

private long delayTime() {

long delay = 86400000;
            System.out.println("delay time:" + delay);
        return delay;

    public void onDestroy() {
         TODO Auto-generated method stub
        if (timer != null){
            Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();

private class BackupTimerTask extends TimerTask {
        public void run() {
            System.out.println("Backup started");
            starting backup here



I call this service

startService(new Intent(this, BackupService.class));

If I set a short interval like 5 minutes, this works fine, but it doesn’t work for long intervals. If I run the service in an Android application, then I can see that my service is running. I think there might be something wrong with the timertask class. How do I solve my problem?

Related Problems and Solutions