# Flush messages before going to sleep

**URL:** <https://community.particle.io/t/flush-messages-before-going-to-sleep/8902>\
**Category:** Firmware\
**Created:** [December 19, 2014, 9:18pm UTC](https://community.particle.io/t/flush-messages-before-going-to-sleep/8902 "2014-12-19T21:18:28Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![mdma](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/mdma/32/1924_2.png) [@mdma](https://community.particle.io/u/mdma)\
**Post date:** [December 21, 2014, 11:09am UTC](https://community.particle.io/t/flush-messages-before-going-to-sleep/8902/4 "2014-12-21T11:09:25Z")

</div>

One way to be completely sure your events have been sent and received is to send a specific “ready to sleep” event last, which you subscribe to, and wait for the subscription to come back. Like this:

```cpp
#include "application.h"

bool canSleep = false; // set to true when the core can sleep
void subscribeHandler(const char* event, const char* data) {
    // data set to the device ID that wants to sleep.
    String id = Spark.deviceID();
    // see if this was a notification from this core that we can sleep
    if (!strcmp(data, id.c_str()))  
        canSleep = true;
}

void setup()
{
    Spark.publish("boot"); // startup events etc..
    Spark.subscribe("sleep", subscribeHandler, MY_DEVICES); // listen for sleep events
}

void loop()
{
    // do other stuff, including publishing events
    
    // publish the sleep event last
    String deviceID = Spark.deviceID();
    Spark.publish("sleep", deviceID.c_str(), 60, PRIVATE);
    
    while (!canSleep) {
        delay(100); // waiting for the event - delay runs the system idle code
    }
    Spark.sleep(SLEEP_MODE_DEEP, 10);
}

```

When I run this, I see the core connect to the cloud, publish boot and sleep events (which I see in the event stream), and wait a few seconds for the response before sleeping.

I hope that’s what you were looking for! 😄

Cheers,  
mat.

---

_[View the full topic](https://community.particle.io/t/flush-messages-before-going-to-sleep/8902)._
