Comments (3)
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.
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.
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)
- `bitflags` dependency for macos only?
- Debouncers don't implement Debug HOT 3
- release with bumped `bitflags` and `filetime` version HOT 2
- (even more) license clarifications: non-standard Artistic-2.0 license HOT 6
- Potential Double Free Issue HOT 2
- Use KqueueWatcher as RecommendedWatcher for iOS
- Breaking Changes v7 HOT 7
- notify crate not actually including license text HOT 2
- Catch no events after saving a watching file with Vim editor HOT 1
- How to write unit tests that exercise a watcher? HOT 3
- Filtering out `log` logs HOT 2
- 【with tokio】After executing `git checkout .` command and then modifying the file, unable to get response to file changes
- Advice for multiple watchers of the same path(s) HOT 2
- How do you dynamically observe files in a directory and log a new file as it appears HOT 1
- My program stops getting events after some time HOT 2
- Watch code is not run inside helper function HOT 2
- `notify-debouncer-full` / `-mini` always enable `notify` default features
- Proposal: Change the serialization format of events HOT 2
- Inconsistent behaviors when root node changes HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from notify.