Red-Folder / Cordova-Plugin-BackgroundService

BackroundService plugin for use with Cordova (PhoneGap)
144 stars 85 forks source link

How to write multiple timers for one Service. #36

Closed MaximShoustin closed 9 years ago

MaximShoustin commented 10 years ago

Hello,

1st of all thanks for great plugin. From example we have timer (by default 60 sec) that runs doWork() in loop every minute and use updateHandler. So far so good.

What if I want to run additional timer lets say other Thread (on the same service MyService) that will run doWork2() each 6 min. Is it posible or I need to write my own. Sorry, don't want to reinvent the wheel.

Thanks,

Red-Folder commented 10 years ago

Its an enhancement that I've been thinking about for a while - allowing multiple timers. I'm afraid that there is a fair amount of work to put into place so unlikely to have any time soon.

Couple of ideas to emulate;

Option 1; Create a separate Background Service for each timer. You would have separate implementation of BackgroundService.java & .js files. Each service would do it's own work and can have it's own timer.

Option 2; Set the timer to run at the fastest frequency you require then have a counter & flag within doWork() to decide to also run the slower frequency work. For the above example, set the timer to run every minute, then within doWork() something like:

this.mCounter++;  // Define as a property of the class - initialize to 0 when defined

if (this.mCounter >= 6) {   // True on every 6th time (thus roughly every 6 minutes)

   // Put your logic here

   this.mCounter = 0;  // Reset the counter
}

Its far from perfect, but may accomplish what you desire.

MaximShoustin commented 10 years ago

Yes, I thought about 2nd option, maybe it's what I will do for a while. Thanks,

Red-Folder commented 10 years ago

Why would you say its good practice? (Option 1, more than 1 service)

Seems fairly comment to have multiple services on Android (native email app for example shows on my phone as 1 process and 2 services).

Plus from a software architecture perspective, it makes sense to separate functionally different operations into different services to keep them isolated and make maintenance easier.

Not saying I'm right, just interested in your point of view ;)

Red-Folder commented 9 years ago

Moved to new repo -> https://github.com/Red-Folder/bgs-core/issues/30