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

Discussion in 'Android Questions' started by Derek Jee, Sep 14, 2015.

  1. Derek Jee

    Derek Jee Active Member Licensed 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,

  2. mangojack

    mangojack Well-Known Member Licensed User

    Try this ... unsure about the midnight hour (0) have not tested..

    Sub Service_Start (StartingIntent As Intent
    0,01)  'schedule service restart ..
    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
    Log("NextRunTime:" & NextRunTime & " Date:" & DateTime.Date(NextRunTime) &  "Time:" & DateTime.Time(NextRunTime))
    End Sub
    Last edited: Sep 14, 2015
    Derek Jee likes this.
  3. Derek Jee

    Derek Jee Active Member Licensed User

    Thank you MJ..

    That works great. and 0 hours works too.

    Thanks so much for your help,

  4. mangojack

    mangojack Well-Known Member Licensed User

    Your Welcome ... The above code was based on a snippet posted by @thedesolatesoul
    Derek Jee likes this.
  5. Erel

    Erel Administrator Staff Member Licensed 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:
    Sub Activity_Create(FirstTime As Boolean)
    Log($"Date: $DateTime{TomorrowAt(01)}"$)
    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, _
    Dim p As Period
       p.Days = 
    Dim tomorrow As Long = DateUtils.AddPeriod(today, p)
    Return tomorrow
    End Sub
    Derek Jee and mangojack like this.
  6. Derek Jee

    Derek Jee Active Member Licensed User

    Thank you, all.. Much appreciated.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice