title: How to use AWS Lambda to run as background task for a limited of time?
body: <p>What I am trying to do is to trigger lambda to run as a background for a limited amount of time (less than limited lambda timeout). I use setInterval and setTimeout but they don't work properly with async/await. Note that the code works if running locally as a node app. I have my code as below: </p>
  
  <pre><code>const mqtt = require('async-mqtt');
  
  module.exports.startPolling = function(event, context, callback) {
      context.callbackWaitsForEmptyEventLoop = false
      let runInterval = setInterval( async() =&gt; {
      await run("tram", "#");
    }, 1000);
    setTimeout(() =&gt; { clearInterval(runInterval)}, 5000); 
  }
  
  
  const run = async(mode, route) =&gt; {  
    console.log("Starting");
      try {
          client = await mqtt.connectAsync('mqtts://mqtt.hsl.fi:8883/');
          await client.subscribe(`/hfp/v2/journey/+/vp/${mode}/${route}`); 
          response = await getMessageAsync(client, "message");
          console.log(response.toString());
          await client.end();
          console.log("Done");
      } catch (e){
          console.log(e.stack);
          process.exit();
      }
  }
  
  const getMessageAsync = (client, ...args) =&gt; {
    return new Promise((resolve, reject) =&gt; {
      client.on(...args, (topic, message) =&gt; {
        resolve(message);
      });
    });
  }
  </code></pre>