1

I've created a Periodic Task that fetches data from my online database every ~8 hours. I must be sure that, when the App opens, it fetches data immediately using a Fetch method, because data must be accessed offline.

The problem comes when my method and the task executes at the same time, like when the task is enqueued for the first time. How to avoid this? So only one of the two runs at a time?.

ॐ Rakesh Kumar
  • 1,188
  • 1
  • 11
  • 21
Davidsal
  • 13
  • 4

1 Answers1

0

you can use Shared Preferences and save a Boolean flag to know if any task is running and proceed the logic based on the flag.

lvl4fi4
  • 1,035
  • 1
  • 8
  • 17
  • I tried this, so far is working. I was using HTTP Post to fetch data, I had to set the ReadTimeout exception, Otherwise, on the event of calling getInputStream() and getting a internet loss, thread would hang and never set the shared preference again to false. Plus, I added a 2 second delay to my OneTimeWork on the Fetch method. – Davidsal Mar 28 '20 at 08:34
  • You can set value in finally statement so you don’t have to worry about exceptions – lvl4fi4 Mar 28 '20 at 10:21
  • At one time, my Worker crashed (Removing App from Recents). So I had to add a "Last Fetch" time data, if has been more than 5 minutes and the Flag is still Active, turn it off and proceed with the Fetch. – Davidsal Mar 28 '20 at 20:48
  • You can set flag off when activity destroyed onstop or on destroyed will work – lvl4fi4 Mar 29 '20 at 06:09