Search code examples
mysqlcronnestjs

How can I delay deletion?


I would like to delay deletion of data from the database. I am using MySQL, nest.js. I heard that CRON is what I need. I want to delete the entry in a week. Can you help me with this? CRON is what I need, or i need to use something another?


Solution

  • A cron job (or at in Windows) or a MySQL EVENT can be created to periodically check for something and take action. The resolution is only 1 minute.

    If you need a very precise resolution, another technique would be required. For example, if you don't want to show a user something that is more than 1 week old to the second, then simply exclude that from the SELECT. That is add something like this to the WHERE: AND created_date >= NOW() - INTERVAL 7 DAY.

    Doing the above gives you the freedom to schedule the actual DELETE for only, say, once a day -- rather than pounding on the database only to usually find nothing to do.

    If you do choose to "pound on the database", be aware of the following problem. If one instance of the deleter script is running for a long time (for any of a number of reasons), it might not be finished before the next copy comes along. In some situations these scripts can stumple over each other to the extent of effectively "crashing" the server.

    That leads to another solution -- a single script that runs forever. It has a simple loop:

    • Do the actions needed (deleting old rows)
    • Sleep 1 -- or 10 or 60 or whatever -- this is to be a "nice guy" and not "pound on the system".

    The only tricky part is making sure that starts up after any server restart or crash of the script.