0

I have deployed my website, in my website user have to complete 10 orders every day, i want to reset orders at 9am everyday. i am using MERN stack. how to reset orders ? i am thinking of sending put requests that modifies user orders to 0 at 9am everyday.

import schedule from 'node-schedule'
const { currentUser } = useSelector((state) => state.user) //using Redux to fetch current user

schedule.scheduleJob('0 9 * * *', async () => {
    try {
      await axios.put(`/details/${currentUser._id}`, {
        dailyOrders: 0,
      })
    } catch (err) {
      console.log(err)
    }
  })

I have tried using node-cron but that didn't work well. it will work only if the user is logged in to the account and have opened the site all the time. If he closes site , node cron will not work.

I have deployed my website! and tried using pm2 start myapi

Furqan
  • 81
  • 6
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Nov 27 '22 at 01:38

1 Answers1

2

There are potentially multiple options, depending on your architecture and the complexity of your backend servers. Also, I strongly believe that this is a task to be completed on the backend servers rather than the client:

  1. You would need a database query to reset all users' orders
  2. This could be a secure route (e.g accessible only to admins through authentication)

Here are some examples of potential solutions depending on your architecture:

  1. If you are using cloud deployment (e.g AWS) you could set up a lambda function to accomplish this and call it on a given schedule via EventBridge (this is basically a serverless cron job)
  2. If you have only one instance of the backend server running you could set up a cron job on that instance (thinking of node-cron job). However, beware of server downtimes and/or multiple servers running at the same time

In a nutshell, there are many ways to accomplish this (it's not one size fit all situation) however this has to be done on the backend servers

jgurbanov
  • 96
  • 4