我正在尝试实现一个每 1.5 小时更新一次天气数据的工作人员。我正在使用PeriodicWorkRequestBuilder并指定了时间,如我的代码所示:
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val workRequest = PeriodicWorkRequestBuilder<WeatherUpdateWorker>(
repeatInterval = 90,
repeatIntervalTimeUnit = TimeUnit.MINUTES,
).setBackoffCriteria(
backoffPolicy = BackoffPolicy.LINEAR,
duration = Duration.ofSeconds(15)
)
.build()
WorkManager.getInstance(applicationContext).enqueueUniquePeriodicWork(
"WeatherUpdateWork",
ExistingPeriodicWorkPolicy.KEEP,
workRequest
)
但是,当我检查 Logcat 时,我的工作日志显示它每 15 分钟执行一次。我该如何解决这个问题?
我已向我的工作人员添加日志以显示其被调用的时间:
@HiltWorker
class WeatherUpdateWorker @AssistedInject constructor(
private val api: WeatherService,
@Assisted val context: Context,
@Assisted workerParameters: WorkerParameters,
private val viewModel: WeatherViewModel
): CoroutineWorker(context, workerParameters) {
override suspend fun doWork(): Result {
try {
val response = api.getWeather()
viewModel.setWeatherResults(response)
val currentTime = System.currentTimeMillis()
saveLastExecutionTime(currentTime)
Log.d("WeatherWorker", "Success, ${currentTime}")
return Result.success()
} catch (e: Exception) {
Log.d("WeatherWorker", "Error")
return Result.retry()
}
}
private fun saveLastExecutionTime(currentTime: Long) {
val sharedPreferences = context.getSharedPreferences("weather_prefs", Context.MODE_PRIVATE)
sharedPreferences.edit().putLong("last_execution_time", currentTime).apply()
}
}
工人工厂:
@HiltAndroidApp
class Application : Application(), Configuration.Provider {
@Inject
lateinit var workerFactory: CustomWorkerFactory
override fun getWorkManagerConfiguration() =
Configuration.Builder()
.setMinimumLoggingLevel(Log.DEBUG)
.setWorkerFactory(workerFactory)
.build()
}
class CustomWorkerFactory @Inject constructor(private val api: WeatherService, private val viewModel: WeatherViewModel): WorkerFactory() {
override fun createWorker(
appContext: Context,
workerClassName: String,
workerParameters: WorkerParameters
): ListenableWorker? = WeatherUpdateWorker(api, appContext, workerParameters, viewModel)
最有可能的是,因为您使用的是
ExistingPeriodicWorkPolicy.KEEP
,所以您现有的 periodicworkrequestbuilder 的周期为 15 分钟,并且您对 1.5 小时周期的更改将被忽略,如文档中所述的 ExistingPeriodicWorkPolicy.KEEP
如果存在具有相同唯一名称的现有待处理(未完成)工作,则不执行任何操作。否则,插入新指定的作品。
最好使用
ExistingPeriodicWorkPolicy.REPLACE
或 ExistingPeriodicWorkPolicy.UPDATE