{"id":13685303,"url":"https://github.com/seniorjoinu/ic-cron","last_synced_at":"2025-04-14T17:06:44.080Z","repository":{"id":44752543,"uuid":"393694904","full_name":"seniorjoinu/ic-cron","owner":"seniorjoinu","description":"Task scheduler for the Internet Computer","archived":false,"fork":false,"pushed_at":"2022-11-11T10:58:00.000Z","size":83,"stargazers_count":39,"open_issues_count":0,"forks_count":9,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-14T17:06:38.651Z","etag":null,"topics":["cron","cronjob","dfinity","internet-computer","rust","scheduler"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/seniorjoinu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-08-07T13:43:46.000Z","updated_at":"2025-01-27T06:47:59.000Z","dependencies_parsed_at":"2023-01-21T14:15:55.672Z","dependency_job_id":null,"html_url":"https://github.com/seniorjoinu/ic-cron","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seniorjoinu%2Fic-cron","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seniorjoinu%2Fic-cron/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seniorjoinu%2Fic-cron/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seniorjoinu%2Fic-cron/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/seniorjoinu","download_url":"https://codeload.github.com/seniorjoinu/ic-cron/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248923766,"owners_count":21183953,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cron","cronjob","dfinity","internet-computer","rust","scheduler"],"created_at":"2024-08-02T14:00:48.499Z","updated_at":"2025-04-14T17:06:44.053Z","avatar_url":"https://github.com/seniorjoinu.png","language":"Rust","funding_links":[],"categories":["Other"],"sub_categories":["ICP \u0026 Cycles"],"readme":"## IC Cron\n\nTask scheduler rust library for the Internet Computer\n\n### Motivation\n\nThe IC provides built-in \"heartbeat\" functionality which is basically a special function that gets executed each time\nconsensus ticks. But this is not enough for a comprehensive task scheduling - you still have to implement scheduling\nlogic by yourself. This rust library does exactly that - provides you with simple APIs for complex background scheduling \nscenarios to execute your code at any specific time, as many times as you want.\n\n### Installation\n\nMake sure you're using `dfx 0.8.4` or higher.\n\n```toml\n# Cargo.toml\n\n[dependencies]\nic-cron = \"0.7\"\n```\n\n### Usage\n\n```rust\n// somewhere in your canister's code\nic_cron::implement_cron!();\n\n#[derive(CandidType, Deserialize)]\nenum TaskKind {\n    SendGoodMorning(String),\n    DoSomethingElse,\n}\n\n// enqueue a task\n#[ic_cdk_macros::update]\npub fn enqueue_task_1() {\n    cron_enqueue(\n        // set a task payload - any CandidType is supported\n        TaskKind::SendGoodMorning(String::from(\"sweetie\")),\n        // set a scheduling interval (how often and how many times to execute)\n        ic_cron::types::SchedulingOptions {\n            1_000_000_000 * 60 * 5, // after waiting for 5 minutes delay once\n            1_000_000_000 * 10, // each 10 seconds\n            iterations: Iterations::Exact(20), // until executed 20 times\n        },\n    );\n}\n\n// enqueue another task\n#[ic_cdk_macros::update]\npub fn enqueue_task_2() {\n    cron_enqueue(\n        TaskKind::DoSomethingElse,\n        ic_cron::types::SchedulingOptions {\n            0, // start immediately\n            1_000_000_000 * 60 * 5, // each 5 minutes\n            iterations: Iterations::Infinite, // repeat infinitely\n        },\n    );\n}\n\n// in a canister heartbeat function get all tasks ready for execution at this exact moment and use it\n#[ic_cdk_macros::heartbeat]\nfn heartbeat() {\n    // cron_ready_tasks will only return tasks which should be executed right now\n    for task in cron_ready_tasks() {\n        let kind = task.get_payload::\u003cTaskKind\u003e().expect(\"Serialization error\");\n      \n        match kind {\n            TaskKind::SendGoodMorning(name) =\u003e {\n                // will print \"Good morning, sweetie!\"      \n                println!(\"Good morning, {}!\", name);\n            },\n            TaskKind::DoSomethingElse =\u003e {\n                ...\n            },\n        };   \n    }\n}\n```\n\n### How many cycles does it consume?\n\nSince this library is just a fancy task queue, there is no significant overhead in terms of cycles.\n\n## How does it work?\n\nThis library uses built-in canister heartbeat functionality. Each time you enqueue a task it gets added to the task\nqueue. Tasks could be scheduled in different ways - they can be executed some exact number of times or infinitely. It is\nvery similar to how you use `setTimeout()` and `setInterval()` in javascript, but more flexible. Each\ntime `canister_heartbeat` function is called, you have to call `cron_ready_tasks()` function which efficiently iterates\nover the task queue and pops tasks which scheduled execution timestamp is \u003c= current timestamp. Rescheduled tasks get\ntheir next execution timestamp relative to their previous planned execution timestamp - this way the scheduler\ncompensates an error caused by unstable consensus intervals.\n\n## Limitations\n\nSince `ic-cron` can't pulse faster than the consensus ticks, it has an error of ~2s. \n\n## Tutorials\n* [Introduction To ic-cron Library](https://dev.to/seniorjoinu/introduction-to-ic-cron-library-17g1)\n* [Extending Sonic With Limit Orders Using ic-cron Library](https://hackernoon.com/tutorial-extending-sonic-with-limit-orders-using-ic-cron-library)\n* [How to Execute Background Tasks on Particular Weekdays with IC-Cron and Chrono](https://hackernoon.com/how-to-execute-background-tasks-on-particular-weekdays-with-ic-cron-and-chrono)\n* [How To Build A Token With Recurrent Payments On The Internet Computer Using ic-cron Library](https://dev.to/seniorjoinu/tutorial-how-to-build-a-token-with-recurrent-payments-on-the-internet-computer-using-ic-cron-library-3l2h)\n\n## API\n\nSee the [example](./example) project for better understanding.\n\n### implement_cron!()\n\nThis macro will implement all the functions you will use: `get_cron_state()`, `cron_enqueue()`, `cron_dequeue()`\nand `cron_ready_tasks()`.\n\nBasically, this macro implements an inheritance pattern. Just like in a regular object-oriented programming language.\nCheck the [source code](ic-cron-rs/src/macros.rs) for further info.\n\n### cron_enqueue()\n\nSchedules a new task. Returns task id, which then can be used in `cron_dequeue()` to de-schedule the task.\n\nParams:\n\n* `payload: CandidType` - the data you want to provide with the task\n* `scheduling_interval: SchedulingInterval` - how often your task should be executed and how many times it should be\n  rescheduled\n\nReturns:\n\n* `ic_cdk::export::candid::Result\u003cu64\u003e` - `Ok(task id)` if everything is fine, and `Err` if there is a serialization\n  issue with your `payload`\n\n### cron_dequeue()\n\nDeschedules the task, removing it from the queue.\n\nParams:\n\n* `task_id: u64` - an id of the task you want to delete from the queue\n\nReturns:\n\n* `Option\u003cScheduledTask\u003e` - `Some(task)`, if the operation was a success; `None`, if there was no such task.\n\n### cron_ready_tasks()\n\nReturns a vec of tasks ready to be executed right now.\n\nReturns:\n\n* `Vec\u003cScheduledTask\u003e` - vec of tasks to handle\n\n### get_cron_state()\n\nReturns a static mutable reference to object which can be used to observe scheduler's state and modify it. Mostly \nintended for advanced users who want to extend `ic-cron`. See the [source code](ic-cron-rs/src/task_scheduler.rs) for \nfurther info.\n\n### _take_cron_state()\n\nReturns (moved) the cron state. Used to upgrade a canister without state cloning. Make sure you're not using `get_cron_state()`\nbefore `_put_cron_state()` after you call this function.\n\n### _put_cron_state()\n\nSets the global state of the task scheduler, so this new state is accessible from `get_cron_state()` function.\n\nParams:\n\n* `Option\u003cTaskScheduler\u003e` - state object you can get from `get_cron_state()` function\n\nThese two functions could be used to persist scheduled tasks between canister upgrades:\n```rust\n#[ic_cdk_macros::pre_upgrade]\nfn pre_upgrade_hook() {\n    let cron_state = _take_cron_state();\n\n    stable_save((cron_state,)).expect(\"Unable to save the state to stable memory\");\n}\n\n#[ic_cdk_macros::post_upgrade]\nfn post_upgrade_hook() {\n    let (cron_state,): (Option\u003cTaskScheduler\u003e,) =\n          stable_restore().expect(\"Unable to restore the state from stable memory\");\n\n    _put_cron_state(cron_state);\n}\n```\n\n## Candid\n\nYou don't need to modify your `.did` file for this library to work.\n\n## Contribution\n\nYou can reach me out here on Github opening an issue, or you could start a thread on Dfinity developer forum.\n\nYou're also welcome to suggest new features and open PR's.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseniorjoinu%2Fic-cron","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fseniorjoinu%2Fic-cron","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseniorjoinu%2Fic-cron/lists"}