I observed one problem regarding periodic JobScheduler. It works as expected as long as the application is not force closed. In this case, the JobScheduler is triggered three times regardless of the fact that the method Schedule() is called only once. In my case, the JobScheduler is started when OnStop() method is called and stopped when the OnStart() method is called. It means that JobScheduler works as long as the application is in the background.
The simplified code inside the JobScheduler:
public override bool OnStartJob(JobParameters @params)
{
CancellationToken token = tokenSource.Token;
bleTask = Task.Run(async() =>
{
await ScanForDevice(@params, token);
},token);
return true;
}
public override bool OnStopJob(JobParameters @params)
{
if(bleTask != null)
{
if (bleTask.Status == TaskStatus.WaitingForActivation)
tokenSource.Cancel();
}
return false;
}
public async Task ScanForDevice(JobParameters jobParams, CancellationToken token)
{
for (int i = 0; i < 120; i++)
{
if (token.IsCancellationRequested)
{
return;
}
await Task.Delay(500); // piece of code is simulated with some delay
}
JobFinished(jobParams, false);
}
I really do not understand why the JobScheduler is executed three times in the case of the application is force closed. It is very interesting if OnStartJob() return value is false then the mentioned problem is not possible to reproduce.