job static method
Enqueues a new job to be processed by the background service.
This method should be called from the main UI isolate.
db: TheSqliteConnectionof the main UI isolate. This is used to insert the job record into thebackground_service_jobstable.jobKey: A string identifier for the task. A JobHandler must be registered for this key via registerJobHandler.payload: Optional data for the job, as aMap<String, dynamic>. This will be JSON-encoded and stored in the database.priority: An integer for job prioritization (higher values are processed first). Currently, this is a basic implementation; more complex prioritization might require adjustments to the job fetching query.maxAttempts: The maximum number of times a job will be retried if it fails.
Returns the ID of the newly inserted job row if successful, otherwise null.
// Assuming 'mainDbConnection' is the SqliteConnection for the UI isolate
await GenericBackgroundService.enqueueJob(
db: mainDbConnection,
jobKey: 'syncUserData',
payload: {'userId': '123', 'forceFullSync': true},
);
Implementation
static Future<int?> job({
required SqliteConnection db, // Pass the main isolate's DB connection
required String jobKey,
Map<String, dynamic>? payload,
int priority = 0,
int maxAttempts = 3,
}) async {
if (!_jobHandlers.containsKey(jobKey)) {
debugPrint(
'BackgroundService: Error - No handler registered for job key "$jobKey".',
);
return null;
}
try {
final String? encodedPayload =
payload != null ? jsonEncode(payload) : null;
final result = await db.execute(
'''
INSERT INTO background_service_jobs (job_key, payload, priority, max_attempts, status)
VALUES (?, ?, ?, ?, 'PENDING')
''',
[jobKey, encodedPayload, priority, maxAttempts],
);
debugPrint(
'BackgroundService: Enqueued job "$jobKey" with ID $result. Payload: $encodedPayload',
);
// Signal the service to check for new jobs if it's running
if (await _service.isRunning()) {
_service.invoke('newJobAvailable');
}
return result.length;
} catch (e, s) {
debugPrint('BackgroundService: Error enqueuing job "$jobKey": $e\n$s');
return null;
}
}