luckycome wait
luckycome wait

Reputation: 35

How to set a timer in android?

timer.scheduleAtFixedRate(function_to_execute, 0, 5000);

I had read above example, but I would like to start the function at specific date and time such as 2013/01/13, 13:15pm.

How to set the timer.scheduleAtFixedRate parameter?

Thank you so much.

Upvotes: 1

Views: 334

Answers (2)

Md Abdul Gafur
Md Abdul Gafur

Reputation: 6201

You need to convert DateTime to Long value then use this Long value in delay time parameter.

Here is example to convert date to long value, same way you convert datetime to Long value and use this long value in delay time parameter.

String str_date="11-June-07";
  DateFormat formatter ; 
  Date date ; 
  formatter = new SimpleDateFormat("dd-MMM-yy");
  date = (Date)formatter.parse(str_date); 
  long longDate=date.getTime();
  System.out.println("Today is " +longDate );

Thanks.

Upvotes: 1

Iswanto San
Iswanto San

Reputation: 18569

The scheduleAtFixedRate method is overloaded.

First :

public void scheduleAtFixedRate(TimerTask task,
                                Date firstTime,
                                long period)

Second (your code used this) :

public void scheduleAtFixedRate(TimerTask task,
                                long delay,
                                long period)

So, to run at spesific time you can use pass Date object for the second parameter.

Date date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss a", Locale.ENGLISH).parse("2013/01/13 13:15 pm");
timer.scheduleAtFixedRate(function_to_execute, date, 5000);

More : Timer.scheduleAtFixedRate

Upvotes: 1

Related Questions