Need some suggestions

susu

Well-Known Member
Licensed User
Longtime User
I'm writing an alarm app, everything seems fine but I stuck with schedule alarm. I want my app will ring on every hour (8:00, 9:00, 10:00...) or every 30 minutes (8:30, 9:00, 9:30...) so I wrote a service that read value from setting file and reschedule it self for 1 hour or 30 minutes. To do that, my service need to start first time exactly.

For example:
1. I set alarm for 30 minutes. If now is 7:16, the first time service start is 7:30. If now is 8:47, the first time service start is 9:00
2. I set alarm for 1 hour. If now is 4:28 the first time service start is 5:00. If now is 6:56 the first time service start is 7:00

I tried to solve it by using this code:

B4X:
hour  = DateTime.GetHour(DateTime.Now)
minute = DateTime.GetMinute(DateTime.Now)

If minute < 30 Then
   timestring = hour & ":30:00"
End If
If minute >= 30 Then
   timestring = (hour + 1) & ":00:00"
End If

settime = DateTime.TimeParse(timestring)

But I think it's not optimized and it will be very complicated if I want to set alarm for every 5 or 10 minutes. Do you have any suggestion? Please share with me. Thank you in advance :)
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
It is much easier to work with the ticks directly:
B4X:
Sub Activity_Create(FirstTime As Boolean)
    Log(DateTime.Time(GetNextTime(60)))
    Log(DateTime.Time(GetNextTime(30)))
    Log(DateTime.Time(GetNextTime(10)))
    Log(DateTime.Time(GetNextTime(5)))
End Sub
Sub GetNextTime(IntervalMinutes As Int) As Long
    Dim t, interval As Long
    interval = IntervalMinutes * DateTime.TicksPerMinute
    t = DateTime.Now
    t = t + interval
    t = t - (t Mod interval)
    Return t
End Sub
 
Upvote 0

susu

Well-Known Member
Licensed User
Longtime User
Yeah! You saved me. Thank you Erel :D
 
Upvote 0
Top