Home > Tutorials > Create a Service that does a schedule task

Create a Service that does a schedule task


Sometimes you need to do a schedule task for a fixed rate (repeatedly), like [check for emails], [check for battery], [update new Facebook status], etc…

The tip here is to use Service and implement a Timer running a TimerTask for an interval.

My sample here is that I like to get Date and Time in every 10 seconds and display a Toast notification to users.

Here how it looks:

Sample Schedule Task

Sample Schedule Task

So I create my own service called TimeService:

public class TimeService extends Service {
	// constant
	public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds

	// run on another Thread to avoid crash
	private Handler mHandler = new Handler();
	// timer handling
	private Timer mTimer = null;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		// cancel if already existed
		if(mTimer != null) {
			mTimer.cancel();
		} else {
			// recreate new
			mTimer = new Timer();
		}
		// schedule task
		mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
	}

	class TimeDisplayTimerTask extends TimerTask {

		@Override
		public void run() {
			// run on another thread
			mHandler.post(new Runnable() {

				@Override
				public void run() {
					// display toast
					Toast.makeText(getApplicationContext(), getDateTime(),
							Toast.LENGTH_SHORT).show();
				}

			});
		}

		private String getDateTime() {
			// get date time in custom format
			SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
			return sdf.format(new Date());
		}

	}

It’s easy to understand, isn’t it?

Next is to register the TimerService to AndroidManifest for identification.

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".TimeService"/>
    </application>

Our last step is to give a call for starting our service when activity executes.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startService(new Intent(this, TimeService.class));
    }

Finally, just run on the phone and see the result.
The implementation is pretty straightforward and simple. You can freely use this way to create some schedule tasks for your applications.

Cheers,
Pete Houston

Categories: Tutorials Tags: , ,
  1. mosayeb masoumi
    May 1, 2020 at 8:13 pm

    helpful thank you

  2. Aditya
    August 11, 2018 at 12:52 am

    Thank you very much. It helped me a lot

  3. Gunjan Sharma
    March 14, 2018 at 3:39 pm

    hello !
    its is not working as a background service . when i close the app i don’t get any notification on the screen.
    I can see the notification only when the app starts.otherwise no notification

    • May 9, 2018 at 11:22 pm

      Add this method to your service, it will run forever unless you stop it from somewhere

      @Override
      public int onStartCommand(Intent intent, int flags, int startId){
      Log.e(TAG, “onStartCommand”);
      super.onStartCommand(intent, flags, startId);
      return START_STICKY;
      }

      START_STICKY will let your service run even when you leave the app

  4. manh
    October 26, 2015 at 10:23 am

    tôi muốn click tạm dừng thì nó sẽ dừng chạy thời gian thì phải làm thế nào

  5. Tsvetoslav
    September 19, 2015 at 3:33 am

    What do you think for this comments – Do not use services for recurring tasks. A recurring task can start a service, which is another matter entirely.

  6. August 28, 2015 at 7:07 pm

    It is not working in mobile device i tried this to run as back ground service for my application.But it not working can you suggest me

  7. Jitin
    June 3, 2015 at 12:39 pm

    Those getting handler error have imported wrong class

    import java.util.logging.Handler;

    Change it to

    import android.os.Handler;

  8. Vishmay patel
    May 25, 2015 at 4:06 pm

    Thank you for nice coding but runinng is only emulator not On Mobile Device So please suggest Me

  9. May 20, 2015 at 12:35 am

    private Handler mHandler = new Handler(); (error: Handler is abstract cannot be instantiated)

    mHandler.post(new Runnable()) (error: Cannot be recognised as a symbol)

    Can anybody solve this error?

  10. juan
    October 3, 2014 at 4:21 pm

    Thank you, your code works perfect

  11. ss
    June 21, 2014 at 12:52 pm

    How to stop this service using a stop service button

    • Hasler Choo
      July 6, 2015 at 2:39 am

      public void onDestroy()
      {
      mTimer.cancel();
      super.onDestroy();
      }

      • mkool
        October 13, 2016 at 2:30 pm

        together with…

        stopService(new Intent(this, TimeService.class));

  12. May 14, 2014 at 3:13 am

    Hi, good and complete example.
    When are you say “run on another Thread to avoid crash
    private Handler mHandler = new Handler();”, what’s mind?

    Is necesary the Handler?

    Greetings.

  13. ColorAnt
    March 23, 2014 at 5:55 pm

    Sorry, parser swallow tags put ‘service’ into ‘activity’.
    This is help me start on 2.2 emulator.

  14. ColorAnt
    March 23, 2014 at 5:52 pm

    Thank you!
    But yoy code have one mistake.
    Put into . On emulator 2.2 this is help me/

  15. Gaurav Mehta
    February 11, 2014 at 6:49 pm

    Let i want to do some task once a day. In that case the service will keep on running in background, which is of no use. dont you think we should use alarm manager here ?

  16. Abdul Qadir
    July 19, 2012 at 6:36 pm

    thank you very much.helps alot

  1. No trackbacks yet.

Leave a comment