•   原文: What's the algorithm behind sleep()? http://stackoverflow.com/questions/175882/whats-the-algorithm-behind-sleep    



    What's the algorithm behind sleep()?




  • bash脚本 sleepFatmawati Achmad Zaenuri/Shutterstock.comFatmawati Achmad Zaenuri / Shutterstock.com The sleep command makes your Linux computer do nothing. Counter-intuitive perhaps, but a period of ...
    bash脚本 sleep

    bash脚本 sleep

    Bash shell on Unity desktop concept
    Fatmawati Achmad Zaenuri/Shutterstock.com Fatmawati Achmad Zaenuri / Shutterstock.com

    The sleep command makes your Linux computer do nothing. Counter-intuitive perhaps, but a period of inactivity is sometimes just what’s needed. This article shows you how to use this Bash shell command effectively.

    sleep命令使您的Linux计算机不执行任何操作。 也许违反直觉,但有时只是需要一段时间不活动。 本文向您展示如何有效使用此Bash shell命令。

    Using sleep is easy. On the command line type sleep, a space, a number, and then press Enter.

    使用sleep很容易。 在命令行上,输入sleep ,一个空格,一个数字,然后按Enter。

    sleep 5

    The cursor will disappear for five seconds and then return. What happened? Using sleep on the command line instructs Bash to suspend processing for the duration you provided. In our example this was five seconds.

    光标将消失五秒钟,然后返回。 发生了什么? 在命令行上使用sleep指示Bash在您提供的持续时间内暂停处理。 在我们的示例中,这是五秒钟。

    No visible output from sleep 5 command

    We can pass durations to sleep in days, hours, and minutes, as well as in seconds. To do this include  a suffix of either d, h, m, or s with the duration. To cause sleep to pause for one day, four hours, seven minutes and five seconds, use a command like this:

    我们可以以天,小时和分钟为单位,以秒为单位传递sleep时间。 为此,请在持续时间后加上d, h, m,s后缀。 要使睡眠暂停一天,四个小时,七分钟零五秒,请使用以下命令:

    sleep 1d 4h 7m 5s

    The s suffix (for seconds) is optional. With no suffix, sleep will treat any duration as seconds. Suppose you wanted to have sleep pause for five minutes and twenty seconds. One correct format of this command is:

    s后缀(秒)是可选的。 没有后缀, sleep会将任何持续时间视为几秒钟。 假设您想让sleep暂停五分钟二十秒。 此命令的一种正确格式是:

    sleep 5m 20

    If you forget to provide the m suffix on the minutes duration, you will instruct sleep to pause for five seconds and then again for twenty seconds. So sleep will pause for 25 seconds.

    如果忘记在分钟数持续时间上提供m后缀,则会指示sleep暂停五秒钟,然后再暂停二十秒钟。 因此, sleep将暂停25秒。

    Many commands require you to provide parameters in a specific order, but sleep is very forgiving. You can provide them in any order and sleep will make sense out of them. You can also provide a floating point number as a parameter. For example, 0.5h is a valid way to indicate you wish sleep to pause for half an hour.

    许多命令要求您以特定顺序提供参数,但是sleep是非常宽容的。 您可以以任何顺序提供它们,而sleep将使它们变得有意义。 您还可以提供浮点数作为参数。 例如,0.5h是指示您希望sleep暂停半小时的有效方法。

    All of the following (increasingly eccentric) commands tell sleep to pause for 10 seconds.


    sleep 10
    sleep 5 5s
    Sleep 1 1 1s 1 1 1s 1 2
    sleep 0.16667m

    在命令前使用睡眠暂停 (Using Sleep to Pause Before a Command)

    The sleep command can be used to give a pause before the execution of a command. This command would pause for 15  seconds and then give a bleep.

    sleep命令可用于在命令执行前暂停。 此命令将暂停15秒,然后发出提示音。

    sleep 15 && echo -en '\007'

    使用睡眠在两个命令之间暂停 (Using Sleep to Pause Between Two Commands)

    You can use sleep to give a pause between two commands. This command would list the files in your Documents directory, pause for five seconds and then change the current working directory to your home directory:

    您可以使用sleep在两个命令之间暂停。 此命令将列出您的Documents目录中的文件,暂停五秒钟,然后将当前工作目录更改为您的主目录:

    ls -R ~/Documents && sleep 5 && cd ~
    Output from two command separated by sleep

    使用睡眠暂停脚本执行 (Using Sleep to Pause Execution of a Script)

    You can use the sleep command in shell scripts to pause execution of the script for a precise amount of time. Typically, you’d do this to allow some process sufficient time to complete before the script continues its processing. You can also use it to rate-limit the requests a script makes to another resource.

    您可以在外壳程序脚本中使用sleep命令在准确的时间内暂停脚本的执行。 通常,您会这样做,以便在脚本继续处理之前,有一些过程有足够的时间来完成。 您还可以使用它来限制脚本对另一个资源的请求的速率。

    To demonstrate exactly that, here is a script that calls out to a Google web service using curl. When you query the web service with the ISBN number of a book, it responds with a dump of JSON data regarding that book. We can parse that data by passing it through the jq utility to retrieve the title of the book. So that the script doesn’t stress the web service, it sleeps for one second between web requests.

    为了确切说明这一点,以下是一个脚本,该脚本使用curl调出Google Web服务。 当用一本书的ISBN号查询Web服务时,它会以与该书有关的JSON数据转储作为响应。 我们可以通过将数据传递给jq实用程序来解析该数据,以检索该书的书名。 为了使脚本不会对Web服务造成压力,它会在两次Web请求之间Hibernate一秒钟。

    Create a file containing the following text, and save it as check_book.sh.


    for book in `cat $1`
     echo $book":"
     curl -s https://www.googleapis.com/books/v1/volumes?q=isbn:$book | jq '.items | .[] | .volumeInfo.title'
     echo ""
     sleep 1
    echo "All done."

    Type the following command to set the execution permissions and make the script executable.


    chmod +x check_book.sh

    The script requires the curl and jq utilities. Use apt-get to install these packages onto your system if you’re using Ubuntu or another Debian-based distribution. On other Linux distributions, use your Linux distribution’s package management tool instead.

    该脚本需要curljq实用程序。 如果您使用的是Ubuntu或其他基于Debian的发行版,请使用apt-get将这些软件包安装到系统上。 在其他Linux发行版上,请改用Linux发行版的程序包管理工具。

    sudo apt-get install curl
    sudo apt-get install jq

    Create a text file containing the following numbers, and save it as books.txt.



    Run the check_book.sh script and pass in the books.txt file as a parameter.


    ./check_book.sh books.txt
    Output of the check_book.sh shell script

    The requests are made to the Google web service at one second intervals. The title of the book will appear shortly after each ISBN number is queried.

    每隔一秒就会向Google网络服务发送一次请求。 查询每个ISBN号后不久,该书的标题就会出现。

    That’s all there is to sleep. The inner workings of the check_book.sh script are beyond the scope of this article. The script was chosen purely to illustrate a valid use of the sleep command. If you wish to read more about the two main components of the script, refer to the  curl project page and the  jq on-line manual.

    这就是sleep的全部。 check_book.sh脚本的内部工作超出了本文的范围。 选择该脚本纯粹是为了说明sleep命令的有效用法。 如果您想阅读更多有关脚本的两个主要组件的信息,请参考curl 项目页面jq 在线手册

    翻译自: https://www.howtogeek.com/410299/how-to-pause-a-bash-script-with-the-linux-sleep-command/

    bash脚本 sleep

  • What late-night snacking has to do with sleep Light-night snacking isn’t just something college students dabble in. It’s a guilt-laden habit that haunts people of all ages, particularly those who ...

    What late-night snacking has to do with sleep

    Light-night snacking isn’t just something college students dabble in. It’s a guilt-laden habit that haunts people of all ages, particularly those who struggle with their weight.
    So what might contribute to the urge for cookies and chips after dinner? A new study suggests it could be sleep deprivation. Even when study participants were allowed to catch up on sleep over the weekend, the cravings persisted.

    For the paper, published in February in the journal Current Biology, researchers used a deliciously rigorous study design to tease out the health effects of not sleeping enough and whether sleeping too little during the week could be offset by a lazy weekend lie-in. (Hat tip to Dr. Perry Wilson at Medscape, who first brought it to our attention.)

    They took 36 healthy volunteers and confined them to a lab for two weeks. First, they had everyone sleep for nine hours per night for three nights. Then they randomly assigned the study participants to one of three groups: a “sleep restriction” group that was allowed to sleep just five hours per night; a control group that had the opportunity to sleep a luxurious nine hours per night; and a “sleep recovery” group that got only five hours per night for five nights, followed by a weekend sleep-in, and two more nights of sleep restriction.

    The researchers gathered data on how much each participant slept and ate, as well as tracking their insulin sensitivity — or how much of the hormone the body needed to secrete in order to manage blood sugar levels. (Low insulin sensitivity, and insulin resistance, is a harbinger of Type 2 diabetes.) They also tracked the participants’ levels of melatonin, another hormone that indicates the body clock’s biological day and night.

    What they found was an indictment of sleep deprivation — even after weekend catch-up sleep — and a potential explanation for why some diets fail. While all three groups ate about the same amount of calories, both of the sleep-deprived groups got more of their calories late in the day, in particular from snacking after dinner. They also gained more weight during the study period compared to the control group. So something about too little sleep spurred a heavier calorie intake later at night, and that difference showed up on the scale.

    Even more alarming, the underslept groups experienced a decrease in their insulin sensitivity — an effect the control group didn’t see — meaning their patterns of eating and sleeping upset their metabolism in ways that could prime them for Type 2 diabetes. And again, weekend recovery sleep failed to protect people from decreased insulin sensitivity.

    It’s only a short-term study, but a well-designed one — and it’s important because it adds to a growing body of evidence that chronic sleep deprivation is a risk factor for both obesity and diabetes. The study is also a reminder that sleep is often missing from the discussion of weight gain and obesity — and it shouldn’t be. To avoid tiredness-induced food cravings, we need to sleep well, consistently, every night.

    So what is it about not sleeping enough that encourages snacking and weight gain?

    There are a few potential explanations for why sleep-deprived folks gain weight more easily. One has to do with the metabolism. Before we get into the details, a quick recap on the three main ways our bodies metabolize energy. We’ve got the “basal metabolic rate” — or how you expend energy when you’re resting. There’s energy expenditure from physical activity. And there’s “diet-induced thermogenesis,” the amount of energy your body uses in order to digest and absorb calories in food. That last one accounts for about 10 percent of the body’s overall energy expenditure.
    Researchers have looked at whether people expend more energy processing a meal later in the day versus earlier and found that, independent of physical activity, the body uses less energy to digest food late in the day. So that means we may convert more calories to fat, instead of burning them off, when we eat late at night.

    Researchers have also repeatedly found that when we’re tired — surprise, surprise — we eat more. In a meta-analysis of 11 studies, the authors showed that people ate 385 extra calories following a night of sleep deprivation. That’s about the same amount as a serving of Häagen-Dazs peanut butter ice cream a day.

    There’s a hormone hypothesis to explain this tendency: A lack of sleep hampers our hunger hormones leptin and ghrelin, potentially contributing to an increase in appetite. Sleep loss may also change how our brains perceive food, Vox’s Brian Resnick has explained. A lack of sleep seems to alter our food-reward system, causing us to get more excited by a cupcake or french fries than we would if we were well rested.

    Besides weight gain, another important finding is that late-night eating is associated with a higher risk of diabetes. Researchers have shown that the body has a harder time managing glucose at night. And the reason is that the circadian system — the body’s internal clock, which is running in every single cell — seems to regulate how the body manages calories at different times of the day.

    ”What we have found is that if you eat an identical meal in the morning or evening, the glucose response is relatively impaired in the evening compared to the morning,” Dr. Frank Scheer, a neuroscientist at Brigham and Women’s Hospital and an associate professor at Harvard Medical School, told Vox previously. “In the evening hours, we can’t cope with the glucose load as well.”
    So not only do we do worse at managing calories when we’re fatigued, and may more often eat late at night, but we tend to eat more calories too.

    While the official recommendation from the American Academy of Sleep Medicine is at least seven hours per night for adults, a third of Americans report sleeping less than that, on average.
    So how can we get more sleep? First, get your basic sleep hygiene in check: Avoid caffeine after lunch, exercise regularly but not too late in the day, and avoid alcohol and heavy meals before bed.
    And, for the love of God, get screens out of your bedroom. “If you can maintain sleep stability, that means you are seeing that same light at the same time every day and your body will pick up on that,” the author of Sleepyhead: The Neuroscience of a Good Night’s Rest, Henry Nicholls, told Vox’s Sean Illing. “And yeah, most people do not appreciate how disruptive artificial light is to the brain. It confuses your brain into thinking it’s daytime when it’s actually bedtime.” Now we know that’s the last thing we want to do if we’re trying to lose weight.


  • JS-如何实现sleep

    千次阅读 2018-09-08 17:22:16
    在JS,要实现sleep,可以异步函数实现,代码: function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function demo() { console.log('Taking a break...'); ...


    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    async function demo() {
      console.log('Taking a break...');
      await sleep(2000);
      console.log('Two seconds later');

    执行demo方法后 ,使用await 关键字等待sleep方法执行完,而demo定时在两秒后执行,以此实现sleep。


  • Wait vs sleep in Java Differences between wait and sleep method in Java Thread is one of the very old question asked in Java interviews. Though both wait and sleep puts thread on waiting state, they
  • Java笔试面试题整理第八波

    万次阅读 多人点赞 2016-06-14 11:07:41
    本系列整理Java相关的笔试面试知识点,其他几篇文章如下:  Java笔试面试题整理第七波  Java笔试面试题整理第六波  Java笔试面试题整理第五波  Java笔试面试题整理第四波 ...What results from the f
  • 如何使用Python sleep()函数?

    千次阅读 2020-10-08 06:30:43
    While developing applications we may need some rest for the ... Python provides sleep()function for different use cases in order to delay program execution. In this tutorial, we will examine P...
  • C语言的sleep、usleep、nanosleep等休眠函数的了解与用法 昨天晚上,无聊中捣鼓「死循环」小代码的时候,想用 休眠 函数来慢慢显示输出结果,免得输出结果闪得太快,看都看不清。 但是,使用 sleep 函数的话,最短...
  • 流利说 Level 4 全文

    万次阅读 多人点赞 2019-05-22 10:52:40
    -What kind of company does her friend’s husband work for? –A start-up company. Christina hasn’t seen her friend for a longtime. The last time they saw each other was three years ago. At that time,...
  • 小程序中 sleep 函数C programming language provides sleep() function in order to wait for a current thread for a specified time. slepp() function will sleep given thread specified time for the current ...
  • golang sleep函数 休眠延时

    万次阅读 2019-10-19 14:02:25
    golang的休眠可以使用time包中的sleep。 函数原型为: func Sleep(d Duration) 其中的Duration定义为: type Duration int64 Duration的单位为 nanosecond。 为了便于使用,time中定义了时间常量: const ...
  • ESP32 支持 Deep-sleep 低功耗模式,通过配置 RTC 外设和 ULP 协处理器的工作模式,可以满足多种应用场景下的低功耗需求。 在 Deep-sleep 模式时,所有由 APB_CLK 驱动的外设、CPU 和 RAM 将掉电,RTC_CLK 继续工作...
  • 直接上SystemClock.sleep()的源代码: public static void sleep(long ms) { /** * uptimeMillis():是指开机到当前时间的时长,区别于System.currentTimeMillis()获取的是系统的时间 * 具体区别在下面会解释...
  • JavaScript Thread.Sleep()

    2019-07-12 17:00:00
    What is the JavaScript version of sleep()? Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current...
  • 前者是生产者,后者就是消费者,这种模式隔离了“做什么”(what)和“怎么做”(How),在功能层面上实现了解耦,体系结构上具备了良好的伸缩性 ,Java就是通过等待和通知机制来实现这种功能的。当一个线程完成了...
  • python3 sleep 延时秒 毫秒

    万次阅读 2019-09-06 14:26:36
    Python中的sleep函数可以传小数进去,然后就可以进行毫秒级的延时了 # 例1:循环输出休眠1秒 import time i = 1 while i = 3: print(i) # 输出i i += 1 time.sleep(1) # 休眠1秒 # 例1:循环输出休眠100毫秒 ...
  • 在 C#/.NET 中,有 Thread.Sleep(0), Task.Delay(0), Thread.Yield(), Task.Yield() 中,有几种不同的让当前线程释放执行权的方法。他们的作用都是放弃当前线程当前的执行权,让其他线程得以调度。但是他们又不太...
  • 比较普遍的C语言游戏

    千次阅读 多人点赞 2019-08-01 19:35:17
    printf(“This is a small game,what you should do is just guess a intange number.\n”); printf(“Now,please guess the number!\n”); srand((unsigned)time(NULL)); while(flag) { int i=rand()%100;//?...
  • 流利说 Level 3 全文

    万次阅读 多人点赞 2019-05-22 10:51:17
    -What did they have to buy on their way to school? –their breakfast.   It usually takes 45 minutes to drive her kids to school, but today it took longer. It took them longer because ...
  • /* What will be run. */ //将要运行的内容 private Runnable target; /* The group of this thread */ //这个线程所属的线程组 private ThreadGroup group; /* The context ClassLoader for this thread */ // ...
  • Sleep in Javascript

    2018-08-22 12:29:48
    Answer from ...https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep I think it's perfectly reasonable to want to perform an action, wait, then perform anothe...
  • ESP8266 in deep sleep

    千次阅读 2015-04-29 14:08:03
    http://blog.hekkers.net/2015/02/26/esp8266-in-deep-sleep/ With the ESP-12 modules on a breadboard adapter I was finally ready for some tinkering. The plan for today was very simple: flash Node
  • sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait()method thread goes in waiting state and it won’t come back automatica
  • linux c 延迟函数 sleep usleep 使用区别

    千次阅读 2020-10-06 19:36:13
    函数 sleep 函数 usleep 区别 函数 sleep 头文件: #include <unistd.h> // 在gcc编译器中,使用的头文件因gcc版本的不同而不同 功 能: 执行挂起指定的秒数 语 法: unsigned sleep(unsigned seconds)...
  • 在有的shell(比如linux中的bash)中sleep还支持睡眠(分,小时) sleep 1 睡眠1秒 sleep 1s 睡眠1秒 sleep 1m 睡眠1分 sleep 1h 睡眠1小时
  • 其实作者Matthew Walker是正里八经的科学家(a professor of neuroscience and psychology at UC Berkeley, the director of the Center for Human Sleep Science, and a former professor of psyschi...
  • Test While You Sleep (and over Weekends)Rajith AttapattuRELAX. I am not referring to offshore development centers, overtime on week- ends, or working the night shift. Rather, I want to draw your ...
  • What is I/O wait?

    2019-04-11 19:52:11
    我个人遇到过一次uninterruptable sleep (D state)的进程,当时很疑惑,当时也没有深究。现在终于在access.redhat.com上搜到了解释。 https://access.redhat.com/articles/2041 What is I/O wait? Updated2012年...
  • What is TimeUnit in Java TimeUnit in Java is a class on java.util.concurrent package, introduced in Java 5 along with CountDownLatch, CyclicBarrier, Semaphore and several other concurrent ...
  • 古月居ROS入门21讲笔记

    万次阅读 多人点赞 2019-07-18 00:05:05
    # 发布消息 person_info_pub.publish(person_msg) rospy.loginfo("Publsh person message[%s, %d, %d]", person_msg.name, person_msg.age, person_msg.sex) # 按照循环频率延时 rate.sleep() if __name__...



1 2 3 4 5 ... 20
收藏数 46,920
精华内容 18,768