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
: TheSqliteConnection
of the main UI isolate. This is used to insert the job record into thebackground_service_jobs
table.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)) {
log(
'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],
);
log(
'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) {
log('BackgroundService: Error enqueuing job "$jobKey": $e\n$s');
return null;
}
}