Setting up a cron tag after create entity

System Information
  • Strapi Version: 3.6.9
  • Operating System: macOs Monterey 12.0.1
  • Database: PostgresSQL
  • Node Version: v14.17.6
  • NPM Version: 6.14.15
  • Yarn Version: 1.22.11

We have the following use case:

  • A new user does register on the platform.
  • The admin must delete or confirm it.
  • After confirmation, each N week by M times a push notification must be sent to the user.

N weeks and M times are set up on another entry on the system.

Can I create a dynamic crontab after each user is confirmed?

Thank you very much

1 Like

My system does something quite similar.

afterCreate → user.status = 0 → Notification to Admin.
Admin confirms → afterUpdate → user.status = 1 and user.notificationsSent = 0

I have just one cronjob that checks each day if there are existing users with user.status 1 and user.notificationsSent < 3.
If true a notification to the user is sent and user.notificationsSent is updated to user.notificationsSent +1.

If the user logs in he is set to user.status 2 and doesn’t get another notification.

You would just need to check the updated_at-Date to archieve your “after x Weeks” demand.

It is not the thing we are looking for: the time will be different for any user since the time begins after the user is confirmed; at that time the cron must init, so checking periodically has no sense.

Hey ! Did you find a solution ?

Thanks

Not a suitable one yet.

I have found something that should do the job using setTimeout()

The most important part is that I pass arguments in the third arg of setTimeout, as dependency to let it keep a pointer to the objects I need (in this case, the Strapi object, with some other args if needed)


setTimeout(
    async ({ strapi, anotherArg }) => {
        await strapi
            .service('api::your-api.your-api')
            .aServiceToRun(anotherArg);
       },
        // Set the time needed in millis.
        // Here we have 10 secs, but I compute some calculations with stored datetimes to estimate the 
        // correct delta time in millis to correctly set the timeout. 
        10000,
       { strapi, anotherArg }
);

Be careful to reload your pending actions at Strapi’s bootstrap if you deal with long periods and the server is subject to restart. If the server is shutted down, all your waiting timeouts are automatically canceled.

I don’t know if this solution is durable, but it seems to work for now.

You just have to repeat the action, but in a way that you cannot reach a stack overflow, so avoid recursive calls as possible.