AlarmManager setRepeating method is not going off exactly every 60 minutes - calendar

my problem is that I have an Alarmmanager that shoudl go off every 60 minutes to a defined time.
This, however, is only working for the first time.
With every next hour passing by Alarmmanager delays its work for 2 or 3 minutes.
Here an example:
hour is set to 4 p. m.
minute is set to 32
timer is set to 60 minutes
Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.HOUR_OF_DAY, hour);
timeOff9.set(Calendar.MINUTE, minute);
am.setRepeating(AlarmManager.RTC_WAKEUP, timeOff9.getTimeInMillis(), timer*60000, pi);
Maybe someone knows why that is so?
I am using API level 15. As of documentation API 19 setRepeating == setInexactRepeating
Thank you very much!

You almost answered your own question by referring to the documentation.
API 19 did indeed infer calls to setRepeating would be treated as setInexactRepeating.
The way to handle this is to set a new alarm when you handle receiving an alarm (>= API 19).
e.g.
#SuppressLint("NewApi")
private void setAlarm(AlarmManager alarmManager, long time,
PendingIntent pIntent, boolean repeat) {
if (android.os.Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pIntent);
} else {
if (repeat) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time,
AlarmManager.INTERVAL_DAY * 7, pIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pIntent);
}
}
}
And then when you receive alarm..
/***
* From version 19 (KitKat) notification that are set repeating aren't
* exact, so the notification needs to be scheduled again each time it is
* received
*/
private void scheduleNextNotification() {
if (android.os.Build.VERSION.SDK_INT < 19) {
return;
}
// set alarm that would have otherwise been repeating
}

Related

Best way to compare times (hours and seconds) without a date in C?

basically I need a time switch in C.
I get the current date and time using strftime.
So at the end I have the information as a string.
For the time switch I only need to compare hours and minutes.
So in pseudocode e.g.:
static bool isSwitchedOn = false;
if(timeOfDay>timeToSwitchOn && !isSwitchedOn) {
switchOn();
isSwitchedOn = true;
}
else if(timeOfDay>=timeToSwitchOf && isSwitchedOn) {
switchOff();
isSwitchedOn = false;
}
One solution would be to use atoi to convert all the times to int and then compare hours and minutes separate.
I saw that I could maybe use difftime, but this requires also a date and I would like not to use dates at all. So and because I already have the times this question is not a duplicate of How do I measure time in C?
EDIT: Sorry, I was not clear enough.
I do not have date information available for the time I compare the current time with.
It is more like on every day at time 20:33 turn on and 20:55 turn off.
Is there a better solution?
Thanks
strftime() is based on a value of struct tm.
Use that value directly for your comparisons, rather than the string.
int timeToSwitchOn = 2033; // switch on a little after 8pm
int timeToSwitchOff = 2055; // switch off just before 9pm
// strftime(..., &tm);
if (tm.tm_hour*100 + tm.tm_min > timeToSwitchOn && !isSwitchedOn) {
switchOn();
isSwitchedOn = true;
}
It is easy to compute a 24 hour based number of minutes from the tm structure instead of converting it to a string with strftime():
timeOfDay = t.tm_hour * 60 + t.tm_min;
Yet your method has a flaw: if the system is started after the timeToSwitchOf and timeToSwitchOn < timeToSwitchOf, the switch would be turned on incorrectly. An error like this might explain why the street lights are sometimes lit in broad day light.
Here is a modified the test:
struct tm t; // this is populated for the current time
...
static bool isSwitchedOn = false;
int timeOfDay = t.tm_hour * 60 * t.tm_min;
if ((timeToSwitchOn < timeToSwitchOff && (timeOfDay >= timeToSwitchOn && timeOfDay < timeToSwitchOff))
|| (timeToSwitchOn > timeToSwitchOff && (timeOfDay >= timeToSwitchOn || timeOfDay < timeToSwitchOff)) {
if (!isSwitchedOn) {
switchOn();
isSwitchedOn = true;
}
} else {
if (isSwitchedOn) {
switchOff();
isSwitchedOn = false;
}
}
}
Note that the special case timeToSwitchOn == timeToSwitchOff here means always off. If you want the system to be always on, set timeToSwitchOn = 0 and timeToSwitchOff = 24 * 60.

Amazon MWS - Request Throttled

After reading the Throttling documentation https://docs.developer.amazonservices.com/en_US/products/Products_Throttling.html and https://docs.developer.amazonservices.com/en_US/dev_guide/DG_Throttling.html , I've started honoring the quotaRemaining and the quotaResetsAt response headers so that I dont go beyond the quote limit. However, whenever I fire a few requests within quick succession, i get the following exception.
The documentation doesnt mention anything about any burst limits. It talks about maximum request quota, but i dont know how that applies to my case. I'm invoking the ListMatchingProducts api
Caused by: com.amazonservices.mws.client.MwsException: Request is throttled
at com.amazonservices.mws.client.MwsAQCall.invoke(MwsAQCall.java:312)
at com.amazonservices.mws.client.MwsConnection.call(MwsConnection.java:422)
... 19 more
I guess I figured it out.
ListMatchingProducts mentions that the Maximum Request Quota is 20. Practically this means that you can fire at max 20 requests in quick succession, but after that you must wait until the Restore Rate "replenishes" your request "credits" (i.e in my case 1 request every 5 seconds).
This Restore rate will (every 5 seconds) start to then re-fill the quota, up to a max of 20 requests. The following code worked for me...
class Client {
private final int maxRequestQuota = 19
private Semaphore maximumRequestQuotaSemaphore = new Semaphore(maxRequestQuota)
private volatile boolean done = false
Client() {
new EveryFiveSecondRefiller().start()
}
ListMatchingProductsResponse fetch(String searchString) {
maximumRequestQuotaSemaphore.acquire()
// .....
}
class EveryFiveSecondRefiller extends Thread {
#Override
void run() {
while (!done()) {
int availablePermits = maximumRequestQuotaSemaphore.availablePermits()
if (availablePermits == maxRequestQuota) {
log.debug("Max permits reached. Waiting for 5 seconds")
sleep(5000)
continue
}
log.debug("Releasing a single permit. Current available permits are $availablePermits")
maximumRequestQuotaSemaphore.release()
sleep(5000)
}
}
boolean done() {
done
}
}
void close() {
done = true
}
}

NAudio trimming mp3 file

I'm trying to trim a mp3 file.
using this code:
private void TrimMp3(string open, string save)
{
using (var mp3FileReader = new Mp3FileReader(open))
using (var writer = File.Create(save))
{
var startPostion = TimeSpan.FromSeconds(60);
var endPostion = TimeSpan.FromSeconds(90);
mp3FileReader.CurrentTime = startPostion;
while (mp3FileReader.CurrentTime < endPostion)
{
var frame = mp3FileReader.ReadNextFrame();
if (frame == null) break;
writer.Write(frame.RawData, 0, frame.RawData.Length);
}
}
}
"open" is the file I'm trimming and "save" is the location I'm saving.
The trimming works but not fully. The new file does start from 60 seconds but it keeps going and not stopping at 90 seconds. For example if the file is 3 minutes it will start at 1 minute and end at 3. Its like the while is always true. What am I doing wrong here?
Thanks in advance!
I have no idea what your Mp3FileReader is doing there. But your while loop looks odd. Does mp3FileRead.ReadNextFrame() also change mp3FileReader.CurrentTime ? If not then there is your problem.
You should atleast do mp3FileReader.CurrentTime + 1Frame. Otherwise your currenttime is never changed and loop will always be true
In NAudio 1.8.0, Mp3FileReader.ReadNextFrame does not progress CurrentTime, although I checked in a fix for that recently.
So you can either get the latest NAudio code, or make use of the SampleCount property on each Mp3Frame to accurately keep track of how far through you are yourself.

Actionscript 2 : Custom Interval Function

I Been messing with Actionscript 2 for about 2 days.. And i have not learned much as im blindly going along with it... But i wrote a function and im curious as to why its not working.. So can someone tell me whats wrong with this code , or even if it could work?
function Interval(Funct:Function, Seconds:Number, Duration:Number){
var MyInterval:Number;
Seconds = Seconds * 1000;
MyInterval = setInterval(Funct, Seconds, Duration);
if(Seconds >= Duration * 1000)
{
clearInterval(MyInterval);
}
return MyInterval;
}
Problem Solved , Solution Below :
function Interval(Funct:Function, Seconds:Number){
Seconds = Seconds * 1000;
_global.i = setInterval(Funct, Seconds);
}
Even though i did want a limit as to when it would stop if specified , im okay with this for now
Thank you Ali-o-kan
Edit : Ran into another problem with this function.. Whenever i enable it more than once using different keys , it leaves it on while creating more whenever i press the button again.. Any way to fix this?

Create a simple countdown in processing

I have searched up so many sites on Google to try and get this to work but NO ONE seems to have this anywhere , and if they do it's just NOT working with my program... What I am trying to achieve is to have a player recoil that when the player gets hit, he has a "x" amount of time between getting hit the first time and the second time.
So I have a Boolean "hit" = false and when he gets hit, it changes to true. Which means he can't get hit again until it's changed to false again.
So I'm trying to set up a function in my program to set a "timer" for "x" amount of seconds IF hit = true and once that timer hits "x" amount of seconds, hit will get switched back to false.
Anyone have any ideas?
Thanks!!
A simple option is to manually keep track of time using millis().
You would use two variables:
one to store elapsed time
one to store the wait/delay time you need
In the draw() method you would check if the difference between the current time (in millis.) and the previously stored time is greater(or equal) to the delay.
If so, this would be your cue to do whatever based on the delay chosen and update the stored time:
int time;
int wait = 1000;
void setup(){
time = millis();//store the current time
}
void draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
println("tick");//if it is, do something
time = millis();//also update the stored time
}
}
Here's a slight variation the updates a 'needle' on screen:
int time;
int wait = 1000;
boolean tick;
void setup(){
time = millis();//store the current time
smooth();
strokeWeight(3);
}
void draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
tick = !tick;//if it is, do something
time = millis();//also update the stored time
}
//draw a visual cue
background(255);
line(50,10,tick ? 10 : 90,90);
}
Depending on your setup/needs, you may choose to wrap something like this into a class that can be reused. This is a basic approach and should work with the Android and JavaScript versions as well (although in javascript you've got setInterval()).
If you're interested in using Java's utilities, as FrankieTheKneeMan suggested, there is a TimerTask class available and I'm sure there are plenty of resources/examples out there.
You can run a demo bellow:
var time;
var wait = 1000;
var tick = false;
function setup(){
time = millis();//store the current time
smooth();
strokeWeight(3);
}
function draw(){
//check the difference between now and the previously stored time is greater than the wait interval
if(millis() - time >= wait){
tick = !tick;//if it is, do something
time = millis();//also update the stored time
}
//draw a visual cue
background(255);
line(50,10,tick ? 10 : 90,90);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>

Resources