work_manager - Timing and tasks
Schedule timed tasks and intent tasks (open-with, share-with, or broadcast-driven). Packaged apps use the same APIs as the built-in scheduler in Auto.js Pro.
Android aggressively limits background work. After registering tasks, ask the user to disable battery optimizations for your app (and allow autostart where OEMs require it), or tasks may not run on time.
"nodejs";
const power_manager = require("power_manager");
if (!power_manager.isIgnoringBatteryOptimizations()) {
console.log("Battery optimization whitelist is not enabled");
power_manager.requestIgnoreBatteryOptimizations();
}The OS does not guarantee exact run times. Whitelist the app where needed (battery, background activity, autostart).
Table of contents
Interfaces
Types
Functions
- addActivityIntentTask
- addBroadcastIntentTask
- addDailyTask
- addIntentTask
- addOneTimeTask
- addWeeklyTask
- getIntentTask
- getTimedTask
- queryIntentTasks
- queryTimedTasks
- removeIntentTask
- removeTimedTask
Types
DateTime
Type: number | string | Date
Accepts a Unix timestamp in ms (number), an ISO / locale date string, or a JavaScript Date instance—depending on the API field.
DaysOfWeek
Union type for days of the week. Accepts English names ("Sunday" ... "Saturday") and also Chinese numerals ("1" ... "7").
TaskType
Type: "TimedTask" | "IntentTask"
Functions
addActivityIntentTask
addActivityIntentTask(task: IntentTaskConfig): Promise<Task>
Registers a task that runs when another app sends an activity intent your script can handle—e.g. Open with in a file manager or Share to Auto.js / your packaged app.
action (required) decides when the task runs, for example:
android.intent.action.VIEW— another app opens a file and picks your handler (MP3, APK, text, …).android.intent.action.SEND— another app shares content (file, text, …).
More actions: Android Intent constants.
dataType (MIME) narrows which content triggers the task, for example:
*/*— any type (use sparingly).application/vnd.android.package-archive— APK packages.text/plain— plain text.video/*— video.image/*— images.
Example: register a handler so plain-text files opened elsewhere run your script:
const { addActivityIntentTask } = require("work_manager");
addActivityIntentTask({
path: "/sdcard/scripts/handle_text.js",
action: "android.intent.action.VIEW",
dataType: "text/plain",
}).then((task) => console.log(`Task ${task} added`));Example handler script (handle_text.js) — reads the incoming Intent, resolves a path, and prints the file:
// handle_text.js
"nodejs";
const { myEngine } = require('engines');
const { getPathFromUri } = require('app');
const { readFileSync } = require('fs');
const intent = myEngine().execArgv.intent;
if (!intent) {
process.exit();
}
const uri = intent.getUri();
const file = getPathFromUri(uri);
console.log(file);
console.log(readFileSync(file, 'utf8'));Parameters
task: Task configuration.
Returns
Promise<Task>
Resolves to the created task.
addBroadcastIntentTask
addBroadcastIntentTask(task: IntentTaskConfig): Promise<Task>
Registers a task that runs when the system (or another component) sends a broadcast whose action matches.
The important field is the intent action: Android fires a matching sticky or ordered broadcast when the event occurs (battery level, screen on/off, package install, …).
Example: run a script when the battery sticky broadcast updates:
"nodejs";
const { android } = require("rhino").Packages;
const Intent = android.content.Intent;
const { addBroadcastIntentTask } = require("work_manager");
addBroadcastIntentTask({
path: "/path/to/script.js",
action: Intent.ACTION_BATTERY_CHANGED,
}).then((task) => console.log(`Task ${task} added`));System actions are listed under Android Intent constants. Some events use component-specific actions (for example legacy ConnectivityManager.CONNECTIVITY_ACTION for connectivity—import ConnectivityManager when you reference it).
Common examples (string values are the same as on Intent):
org.autojs.autojs.action.startup— Auto.js / Auto.js Pro startup hook (use with autostart so your handler actually runs).Intent.ACTION_BOOT_COMPLETED— user has finished booting (requires appropriate manifest / OEM policy).Intent.ACTION_SCREEN_OFF/Intent.ACTION_SCREEN_ON— display off / on.Intent.ACTION_USER_PRESENT— user dismissed the keyguard.Intent.ACTION_BATTERY_CHANGED— battery level / status (sticky intent).Intent.ACTION_POWER_CONNECTED/Intent.ACTION_POWER_DISCONNECTED— charger plugged / unplugged.ConnectivityManager.CONNECTIVITY_ACTION— legacy network connectivity changes.Intent.ACTION_PACKAGE_ADDED/ACTION_PACKAGE_REMOVED/ACTION_PACKAGE_REPLACED— apps installed / removed / updated.Intent.ACTION_HEADSET_PLUG— wired headset plugged or unplugged.Intent.ACTION_CONFIGURATION_CHANGED— locale, orientation, font scale, etc.Intent.ACTION_TIME_TICK— fires about once per minute while awake.
Inside the task script, read the delivered Intent with require("engines").myEngine().execArgv.intent and pull extras as needed.
Example task body for ACTION_BATTERY_CHANGED — prints the reported battery level from extras:
"nodejs";
const { myEngine } = require("engines");
const { android } = require("rhino").Packages;
const intent = myEngine().execArgv.intent;
if (!intent) {
process.exit();
}
const BatteryManager = android.os.BatteryManager;
const level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
console.log("Battery:", level);Parameters
task: Task configuration.
Returns
Promise<Task>
Resolves to the created task.
addDailyTask
addDailyTask(task: TimedTaskConfig): Promise<Task>
Adds a daily alarm: only the clock time matters; the calendar date is ignored. Example: run every day at 13:14.
Example
"nodejs";
const { addDailyTask } = require("work_manager");
addDailyTask({
path: "/path/to/script.js",
time: new Date(0, 0, 0, 13, 14, 0),
}).then((task) => console.log(task));Parameters
task: Task configuration.
Returns
Promise<Task>
addIntentTask
addIntentTask(task: IntentTaskConfig): Promise<Task>
Generic entry point for intent tasks. In practice you almost always want the specific helpers:
addBroadcastIntentTask— react to a broadcastaction.addActivityIntentTask— react to VIEW / SEND and similar activity intents.
Prefer those two instead of calling addIntentTask directly.
Parameters
task: Task configuration.
Returns
Promise<Task>
addOneTimeTask
addOneTimeTask(task: TimedTaskConfig): Promise<Task>
Schedules a one-shot task and removes it from the scheduler after it runs once.
Example: run once on 21 May 2021 at 13:14 (remember: Date months are 0-based, so May → month 4).
Example
"nodejs";
const { addOneTimeTask } = require("work_manager");
addOneTimeTask({
path: "/sdcard/to/script.js",
time: new Date(2021, 4, 21, 13, 14, 0),
}).then((task) => console.log(task));Parameters
task: Task configuration.
Returns
Promise<Task>
addWeeklyTask
addWeeklyTask(task: any): Promise<Task>
Adds a weekly task: same time of day on each selected weekday.
Example: run every Monday and Tuesday at 13:14.
Example
"nodejs";
const { addWeeklyTask } = require("work_manager");
addWeeklyTask({
path: "/sdcard/scripts/test.js",
// Mon Jun 21 2021 13:14:00 GMT+0800
time: 1624252440000,
daysOfWeek: ["Monday", "Tuesday"],
}).then((task) => console.log(task));Parameters
task: Weekly task configuration.
Returns
Promise<Task>
getIntentTask
getIntentTask(id: number): Promise<Task | null>
Loads a single intent task by its numeric id, or null if it does not exist.
Parameters
id: Task id.
Returns
Promise<Task | null>
Resolves to the task, or null if not found.
getTimedTask
getTimedTask(id: number): Promise<Task | null>
Loads a timed task by id, or null if it does not exist.
Parameters
id: Task id.
Returns
Promise<Task | null>
Resolves to the task, or null if not found.
queryIntentTasks
queryIntentTasks(query?: IntentTaskQuery ): Promise<Task[]>
Query intent tasks with optional filters (script path, action, …).
Example
"nodejs";
const { android } = require("rhino").Packages;
const Intent = android.content.Intent;
const { queryIntentTasks, addBroadcastIntentTask } = require("work_manager");
async function main() {
const task = await addBroadcastIntentTask({
path: "/sdcard/to/script.js",
action: Intent.ACTION_BATTERY_CHANGED,
});
// Query all intent tasks
const tasks = await queryIntentTasks();
console.log(tasks);
}
main();Parameters
query: Query conditions.
Returns
Promise<Task[]>
queryTimedTasks
queryTimedTasks(query?: TimedTaskQuery ): Promise<Task[]>
Query timed tasks (daily / weekly / one-shot) with optional filters such as path.
Example
"nodejs";
const work_manager = require("work_manager");
const file = "/path/to/script.js";
async function main() {
const task = await work_manager.addWeeklyTask({
path: file,
time: 1624252440000,
daysOfWeek: ['Sunday'],
});
const tasks = await work_manager.queryTimedTasks({
path: file
});
for (const t of tasks) {
console.log("delete:", t);
console.log(await work_manager.removeTimedTask(t.id));
}
}Parameters
query: Query conditions.
Returns
Promise<Task[]>
removeIntentTask
removeIntentTask(id: number): Promise<boolean>
Removes an intent task by id.
Parameters
id: Task id.
Returns
Promise<boolean>
Returns true if a task was removed, false if no matching task exists.
removeTimedTask
removeTimedTask(id: number): Promise<boolean>
Removes a timed task by id.
Parameters
id: Task id.
Returns
Promise<boolean>
Returns true if a task was removed, false if no matching task exists.
