Skip to content

Commit

Permalink
Allow non-sync futures (#18)
Browse files Browse the repository at this point in the history
* tests: run async tests only when "async" feature is enabled

Signed-off-by: Eliad Peller <eliad.peller@wiz.io>

* async_cron: don't require Future to be Sync

Signed-off-by: Eliad Peller <eliad.peller@wiz.io>

---------

Signed-off-by: Eliad Peller <eliad.peller@wiz.io>
  • Loading branch information
eliad-wiz authored Nov 12, 2024
1 parent cb5e379 commit 5968509
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,10 @@ chrono = "0.4"
cron = "0.12"
thiserror = "1.0"
crossbeam-channel = "0.5"
tokio = { version = "1.25", optional = true , features = ["sync", "rt-multi-thread", "time", "macros"] }
tokio = { version = "1.25", optional = true, features = ["sync", "rt-multi-thread", "time", "macros"] }
futures = { version = "0.3.26", optional = true }

[[example]]
name = "async_simple"
path = "examples/async_simple.rs"
required-features = ["async"]
4 changes: 2 additions & 2 deletions src/async_cron.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ where
pub async fn add_fn<F, T>(&mut self, spec: &str, f: F) -> Result<usize>
where
F: 'static + Fn() -> T + Send + Sync,
T: 'static + Future<Output = ()> + Send + Sync,
T: 'static + Future<Output = ()> + Send,
{
let schedule = cron::Schedule::from_str(spec)?;
self.schedule(schedule, f).await
Expand Down Expand Up @@ -184,7 +184,7 @@ where
async fn schedule<F, T>(&mut self, schedule: cron::Schedule, f: F) -> Result<usize>
where
F: 'static + Fn() -> T + Send + Sync,
T: 'static + Future<Output = ()> + Send + Sync,
T: 'static + Future<Output = ()> + Send,
{
let next_id = self.next_id.fetch_add(1, Ordering::SeqCst);

Expand Down
9 changes: 8 additions & 1 deletion tests/async.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#[cfg(feature = "async")]
#[cfg(test)]
mod tests {
use std::cell::UnsafeCell;
use std::sync::Arc;

use chrono::{FixedOffset, Local, TimeZone};
Expand Down Expand Up @@ -28,9 +30,14 @@ mod tests {

cron.add_fn("* * * * * *", move || {
let counter1 = Arc::clone(&counter1);

// use UnsafeCell to make sure we can still use non-Sync types
let mut inc: UnsafeCell<usize> = 1.into();

async move {
let mut value = counter1.lock().await;
*value += 1;
let inc = *inc.get_mut();
*value += inc;
}
})
.await
Expand Down

0 comments on commit 5968509

Please sign in to comment.