CSharp
CSharp

Reputation: 1486

Docker Container to run a period process which populates a database

Using docker compose I have created a docker stack with a web front-end and a mongo database back-end. I need a process to run periodically, say once an hour, which populates my database by executing a node.js script. Ideally I would like something that will run as a docker container so I can simply define the node.js script and add the container to my docker-compose.yml file. I've read through some posts that use cron to automate simple tasks. Would this approach be extendable to perform updates of my database too?

Upvotes: 1

Views: 146

Answers (1)

b0gusb
b0gusb

Reputation: 4731

cron can do the trick. Given that you're going to run a Node.js script, why don't you implement the scheduling in the script itself. Using async for example:

async function sleep(millis) {
    return new Promise(resolve => setTimeout(resolve, millis));
}

async function updatedb() {
    while(true)
        console.log("updating database");
        // ... update the database, await if necessary
        // then sleep one hour
        await sleep(60 * 60 * 1000);
    }
}

updatedb();

Set the script as the command to run (CMD) within the container

CMD ["nodejs", "/path/to/updatedb.js"]

This has the advantage of having everything in one place and avoids additional crontab configuration. Hope it helps.

Upvotes: 1

Related Questions