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;

	public IBinder onBind(Intent intent) {
		return null;

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

	class TimeDisplayTimerTask extends TimerTask {

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

				public void run() {
					// display toast
					Toast.makeText(getApplicationContext(), getDateTime(),


		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.

        android:theme="@style/AppTheme" >
            android:label="@string/title_activity_main" >
                <action android:name="android.intent.action.MAIN" />

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

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

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

    public void onCreate(Bundle savedInstanceState) {

        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.

Pete Houston

Categories: Tutorials Tags: , ,
  1. 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

  2. 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

  3. 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.

  4. 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

  5. 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;

  6. 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

  7. 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?

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

    Thank you, your code works perfect

  9. 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()

      • mkool
        October 13, 2016 at 2:30 pm

        together with…

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

  10. 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?


  11. 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.

  12. 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/

  13. 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 ?

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

    thank you very much.helps alot

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: