Here is my worker class:
public class DataContinueWork extends Worker {
public DataContinueWork(Context context,
WorkerParameters workerParams) {
super(context, workerParams);
}
@Override
public Result doWork() {
addInDatabase();
return Result.Success.success();
}
private void addInDatabase() {
DatabaseHelper database = Room.databaseBuilder(getApplicationContext(), DatabaseHelper.class, "database").build();
DatabaseModel databaseModel = new DatabaseModel();
Date date = new Date();
@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE d MMM yyyy HH:mm:ss aaa");
Log.e("avrge", "getArge - --->>>> " + tempTotal1 / tempCounter1);
databaseModel.setOtTemp(String.valueOf(tempTotal1 / tempCounter1));
tempTotal1 = 0;
tempCounter1 = 0;
Log.e("avrge", "val tempTotal cont - --->>>> " + tempTotal1 + " " + tempCounter1);
databaseModel.setTime(simpleDateFormat.format(date));
database.getDao().insert(databaseModel);
}
}
And here initialize my work in background:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(DataContinueWork.class,
1, TimeUnit.MINUTES,1 ,TimeUnit.SECONDS).build();
WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(String.valueOf(periodicWork),
ExistingPeriodicWorkPolicy.KEEP, periodicWork);
return super.onStartCommand(intent, flags, startId);
}
But the worker not working every minute so now what do I do?
I want to add data to the database every minute but the worker not working properly.
Data add but not added every minute see database log here
From the docs
"Periodic work has a minimum interval of 15 minutes."
So you cannot use a PeriodicWorkRequest.
In some experimentation I did with Work Manager, to get a periodic work request around every minute you can create a OneTimeWorkRequest
and then setInitialDelay
of 1 minute and then Observe the WorkRequest for the three completed states and then trigger the next OneTimeWorkRequest
when the first had finished.
If you try and re-use the same work request for each time you might have problems with using the same ID, but you can work around that with a kludge of pruning the work manager to remove old requests before scheduling the next.
The are also other ways to trigger multiple OneTimeWorkRequest's with a minutes delay.