@@ -872,6 +872,72 @@ pub fn sleep(dur: Duration) {
872
872
imp:: Thread :: sleep ( dur)
873
873
}
874
874
875
+ /// Puts the current thread to sleep until the specified deadline has passed.
876
+ ///
877
+ /// The thread may still be asleep after the deadline specified due to
878
+ /// scheduling specifics or platform-dependent functionality. It will never
879
+ /// wake before.
880
+ ///
881
+ /// This function is blocking, and should not be used in `async` functions.
882
+ ///
883
+ /// # Platform-specific behavior
884
+ ///
885
+ /// This function uses ['sleep'] internally, see its platform-specific behaviour.
886
+ ///
887
+ ///
888
+ /// # Examples
889
+ ///
890
+ /// A simple game loop that limits the game to 60 frames per second.
891
+ ///
892
+ /// '''no_run
893
+ /// # use std::time::{Duration, Instant};
894
+ /// # use std::thread;
895
+ /// #
896
+ /// let max_fps = 60.0;
897
+ /// let frame_time = Duration::from_secs_f32(1.0/max_fps);
898
+ /// let mut next_frame = Instant::now();
899
+ /// loop {
900
+ /// thread::sleep_until(next_frame);
901
+ /// next_frame += frame_time;
902
+ /// update();
903
+ /// render();
904
+ /// }
905
+ /// '''
906
+ ///
907
+ /// A slow api we must not call too fast and which takes a few
908
+ /// tries before succeeding. By using `sleep_until` the time the
909
+ /// api call takes does not influence when we retry or when we give up
910
+ ///
911
+ /// ```no_run
912
+ /// # use std::time::{Duration, Instant};
913
+ /// # use std::thread;
914
+ /// #
915
+ /// # const MAX_DURATION: Duration = Duration::from_secs(10);
916
+ /// #
917
+ /// let deadline = Instant::now() + MAX_DURATION;
918
+ /// let delay = Duration::from_millis(250);
919
+ /// let mut next_attempt = Instant::now();
920
+ /// loop {
921
+ /// if Instant::now() > deadline {
922
+ /// break Err(()),
923
+ /// }
924
+ /// if let Ready(data) = slow_web_api_call() {
925
+ /// break Ok(data),
926
+ /// }
927
+ ///
928
+ /// next_attempt = deadline.min(next_attempt + delay);
929
+ /// thread::sleep_until(next_attempt);
930
+ /// }
931
+ /// ```
932
+ #[ unstable( feature = "thread_sleep_until" , issue = "todo" ) ]
933
+ pub fn sleep_untill ( deadline : Instant ) {
934
+ let now = Instant :: now ( ) ;
935
+
936
+ if let Some ( delay) = deadline. checked_duration_since ( now) {
937
+ thread:: sleep ( delay) ;
938
+ }
939
+ }
940
+
875
941
/// Used to ensure that `park` and `park_timeout` do not unwind, as that can
876
942
/// cause undefined behaviour if not handled correctly (see #102398 for context).
877
943
struct PanicGuard ;
0 commit comments