Code Monkey home page Code Monkey logo

Comments (3)

0xpr03 avatar 0xpr03 commented on June 10, 2024

for result in rx {

That's where you are looping endlessly, waiting for an event.
Same solution as in the examples for notify, use a tokio mpsc channel and .await for new events somewhere. Note the linked (await) example here doesn't spawn something, it just awaits endlessly for new events.

from notify.

Hellager avatar Hellager commented on June 10, 2024

After switch to tokio and make functions async, still stuck at the same position, am i still missing something?

use notify::{RecursiveMode, Watcher, ReadDirectoryChangesWatcher};
use std::{thread, path::Path, time::Duration};
use chrono::prelude::*;
use notify_debouncer_full::{new_debouncer, Debouncer, FileIdMap, DebounceEventResult};
use tokio::runtime::{Runtime, Handle};
use tokio::sync::mpsc;

fn get_runtime_handle() -> (Handle, Option<Runtime>) {
    match Handle::try_current() {
        Ok(h) => (h, None),
        Err(_) => {
              let rt = Runtime::new().unwrap();
              (rt.handle().clone(), Some(rt))
            }
    }
}

pub struct NotifyHandler {
    pub notify_watcher: Option<Debouncer<ReadDirectoryChangesWatcher, FileIdMap>>,
}

impl NotifyHandler {    
    pub async fn initialize_notify_scheduler(&mut self) {
        let (mut tx, mut rx) = tokio::sync::mpsc::channel(1);
    
        let debouncer = new_debouncer(Duration::from_secs(3), None, move |result: DebounceEventResult| {
            let (handle, _rt) = get_runtime_handle();
            handle.block_on(async {
                tx.send(result).await.unwrap();
            })
        });
    
        match debouncer {
            Ok(watcher)=> {
                println!("Initialize notify watcher success");
                self.notify_watcher = Some(watcher);

                while let Some(res) = rx.recv().await {
                    match res {
                        Ok(events) => {
                            println!("events: {:?}", events);
                        },
                        Err(errors) => {
                            println!("erros: {:?}", errors)
                        }
                    }
                }
            },
            Err(error) => {
                println!("{:?}", error);
            }
        }
    }

    
    pub fn watch(&mut self, path: &str) -> notify::Result<()> {
        let watch_path = Path::new(path);

        if watch_path.exists() {
            let is_file = watch_path.is_file();
            println!("Valid path {} is file {}", path, is_file);
        } else {
            println!("watch path {:?} not exists", watch_path);
        }

        if let Some(mut watcher) = self.notify_watcher.take() {
            watcher
                .watcher()
                .watch(watch_path, RecursiveMode::Recursive)?;         

            watcher
                .cache()
                .add_root(watch_path, RecursiveMode::Recursive);                    
        }

        Ok(())
    }
}

#[tokio::main]
async fn main() {
    let mut notifier: NotifyHandler = NotifyHandler { notify_watcher: None };

    notifier.initialize_notify_scheduler().await;

    loop {
        thread::sleep(Duration::from_secs(2));

        let time: DateTime<Local> = Local::now();

        println!("{}: Hello, world!", time.format("%Y-%m-%d %H:%M:%S").to_string());
    }
}

from notify.

Hellager avatar Hellager commented on June 10, 2024

For any one who may have the same question, here' the working solution.
Is there some way to make notify debounce watcher async?

from notify.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.