# mod\_cron

Source: https://zotonic.com/docs/1811/mod_cron

URI: https://zotonic.com/id/1811

Language: en



Provides periodic tick notifications and module-defined cron job scheduling.

This module both sends periodic *tick* notifications (which can be observed by modules) and reads each module’s `-mod_cron_jobs` attribute to register scheduled jobs at specific intervals.

tick
----

For periodic tasks the system has various periodic tick events. They are named after their interval *s* for seconds, *m* for minutes, and *h* for hours.

- tick\_1s
- tick\_1m
- tick\_10m
- tick\_15m
- tick\_30m
- tick\_1h
- tick\_2h
- tick\_3h
- tick\_4h
- tick\_6h
- tick\_12h
- tick\_24h

### Example

Check something every hour.

```erlang
-include_lib("kernel/include/logger.hrl").

observe_tick_1h(tick_1h, Context) ->
    ?LOG_INFO("And another hour has passed..."),
    do_something(Context).
```

The return value is ignored.

The *tick* observers are called one by one in a separate process. So a slow handler can delay the other handlers.

`-mod_cron_jobs` Module Attribute
---------------------------------

Modules can define periodic jobs using the module attribute `-mod_cron_jobs`.

`mod_cron` reads this attribute from active modules and registers each job with `erlcron`.

Each entry is one of:

- `{RunWhen, {Module, Function, Args}}`
- `{RunWhen, {Module, Function, Args}, JobOpts}`

Where:

- `RunWhen` is an `erlcron` schedule tuple (daily/weekly/every/etc.).
- `{Module, Function, Args}` is the MFA to call.
- `JobOpts` are optional `erlcron` job options.

Important: `mod_cron` appends the site `Context` as the last argument when calling the MFA, so the target function must accept one extra argument.

### Example

```erlang
-mod_depends([cron]).
-mod_cron_jobs([
    {{weekly, mon, {10, 0, 0}}, {?MODULE, send_weekly_reminders, []}}
]).

send_weekly_reminders(Context) ->
    Events = get_this_weeks_events(Context),
    send_email_reminders(Events, Context).
```

This schedules `send_weekly_reminders/1` every Monday at 10:00 UTC.

Scheduling syntax is provided by `erlcron`, see: <https://hexdocs.pm/erlcron/readme.html>

Accepted Events
---------------

This module handles the following notifier callbacks:

- `observe_tick_1h`: Run periodic hourly cron checks and enqueue due jobs.

License: 

Attribution: 

Related resources: https://zotonic.com/api/agent/related/1811?language=en


## API access

- [API help](<https://zotonic.com/api-help>)
- [OpenAPI specification](<https://zotonic.com/openapi.json>)
- [This resource as JSON](<https://zotonic.com/api/agent/resource/1811?language=en>)
