Android Question Set service to run tomorrow at 12:01 am

Derek Jee

Active Member
Licensed User
Longtime User
Hi there

Can anyone suggest how to start a service 'tomorrow' at 12:01. Not sure I am using the date formatting correctly as I get errors. Not actually sure I am doing the right thing at all so some code would be nice..

Thank you in advance,

Derek.
 

mangojack

Well-Known Member
Licensed User
Longtime User
Try this ... unsure about the midnight hour (0) have not tested..

B4X:
Sub Service_Start (StartingIntent As Intent) 
     ScheduleNextServiceStart(0,01)  'schedule service restart ..
     StopService("")
End Sub

Sub ScheduleNextServiceStart(Hours As Int, Minutes As Int) 
 
    Dim CurrentTime, Today, NextRunTime, HourMinTicks As Long 
 
    DateTime.DateFormat = "dd-MM-yyyy"
    HourMinTicks = Hours * DateTime.TicksPerHour + Minutes * DateTime.TicksPerMinute

   'calc ticks up to start of today ... 00:00am
   Today = DateTime.DateParse(DateTime.Date(DateTime.Now))
   'calc ticks up to current/present time
   CurrentTime = DateTime.Now - Today

   If HourMinTicks > CurrentTime Then
       'Time has Not passed, schedule For Today
       NextRunTime = Today + HourMinTicks
   Else 'Schedule for tomorrow
       NextRunTime = Today + DateTime.TicksPerDay + HourMinTicks
   End If
 
   StartServiceAt("",NextRunTime,True)
 
   Log("NextRunTime:" & NextRunTime & " Date:" & DateTime.Date(NextRunTime) &  "Time:" & DateTime.Time(NextRunTime))
 
End Sub
 
Last edited:
Upvote 0

Derek Jee

Active Member
Licensed User
Longtime User
Thank you MJ..

That works great. and 0 hours works too.

Thanks so much for your help,


Derek.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
The code above will not work correctly during the two days that the timezone changes (DST effects).

You can use this code to get the correct time value:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Log($"Date: $DateTime{TomorrowAt(0, 1)}"$)
End Sub

Sub TomorrowAt (Hours As Int, Minutes As Int) As Long
   Dim today As Long = DateUtils.SetDateAndTime(DateTime.GetYear(DateTime.Now), _
     DateTime.GetMonth(DateTime.Now), _
     DateTime.GetDayOfMonth(DateTime.Now), _
     Hours, _
     Minutes, 0)
   Dim p As Period
   p.Initialize
   p.Days = 1
   Dim tomorrow As Long = DateUtils.AddPeriod(today, p)
   Return tomorrow
End Sub
 
Upvote 0

Derek Jee

Active Member
Licensed User
Longtime User
Thank you, all.. Much appreciated.
 
Upvote 0
Top