Agendando Tarefas com a API de Alarmes
Execute trabalhos periódicos e atrasados em segundo plano de forma confiável em um service worker do Manifest V3 usando chrome.alarms.
Agendando Tarefas com a API de Alarmes é uma aula grátis de Browser Extensions Development (Chrome & Edge) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Browser Extensions Development (Chrome & Edge), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Browser Extensions Development (Chrome & Edge) inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Not setInterval
In Manifest V3 the service worker unloads when idle, so setTimeout and setInterval are unreliable for scheduled work. The alarms API survives this by waking the worker when it is time to run.
Declaring the Permission
Add the alarms permission to the manifest before using the API.
{
"permissions": ["alarms"]
}Creating a One-Time Alarm
Use alarms.create with delayInMinutes for a single delayed task.
chrome.alarms.create('cleanup', { delayInMinutes: 5 })Creating a Repeating Alarm
Add periodInMinutes to make the alarm fire again and again on a schedule.
chrome.alarms.create('sync', { periodInMinutes: 30 })Handling the Alarm
Listen for onAlarm at the top level of your service worker. The alarm object tells you which one fired.
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'sync') {
doSync()
}
})Register Listeners at the Top Level
Because the worker restarts, register onAlarm synchronously when the script first runs, not inside an async callback, or the wake-up may be missed.
// top of background.js, runs on every wake
chrome.alarms.onAlarm.addListener(handleAlarm)Minimum Period
For packed extensions the smallest repeating period is about one minute. Shorter intervals are clamped, so do not rely on second-level timing.
chrome.alarms.create('tick', { periodInMinutes: 1 })Inspecting Alarms
Use alarms.get or alarms.getAll to check what is scheduled, useful for avoiding duplicates.
const a = await chrome.alarms.get('sync')
if (!a) chrome.alarms.create('sync', { periodInMinutes: 30 })Clearing Alarms
Remove a single alarm with clear or all of them with clearAll when a feature is turned off.
chrome.alarms.clear('sync')
chrome.alarms.clearAll()Recreating on Install
Set up your alarms in the onInstalled event so they exist from the moment the extension is installed or updated.
chrome.runtime.onInstalled.addListener(() => {
chrome.alarms.create('sync', { periodInMinutes: 30 })
})Keeping Work Short
The worker may unload soon after the alarm. Keep the task quick, persist state to storage, and avoid long-running loops that could be cut off.
Quick Check
Test your alarms knowledge.
Recap
You learned reliable scheduling:
- Use
alarms.createwith delay or period - Handle
onAlarmregistered at the top level - Respect the ~1 minute minimum period
- Inspect, clear, and recreate alarms
- Keep alarm work short
The alarms API makes background scheduling dependable under Manifest V3.
Perguntas Frequentes
A aula “Agendando Tarefas com a API de Alarmes” é grátis?
Sim — o texto completo de “Agendando Tarefas com a API de Alarmes” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Browser Extensions Development (Chrome & Edge), atualize para CoddyKit PRO. O curso de Browser Extensions Development (Chrome & Edge) inclui 4 aulas no total.
O que vou aprender em “Agendando Tarefas com a API de Alarmes”?
Execute trabalhos periódicos e atrasados em segundo plano de forma confiável em um service worker do Manifest V3 usando chrome.alarms. Você pratica Browser Extensions Development (Chrome & Edge) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Browser Extensions Development (Chrome & Edge)?
Nenhuma experiência prévia é necessária. Browser Extensions Development (Chrome & Edge) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Agendando Tarefas com a API de Alarmes”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Browser Extensions Development (Chrome & Edge)?
Sim. Cada aula de Browser Extensions Development (Chrome & Edge) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Gerenciamento e Controle de Abas
- Envio Programático de Formulários
- Automatizando Interações do Usuário
- Agendando Tarefas com a API de Alarmes