Scheduled Work For Task Reset Code not Working. Help!

I’m working for a Attendance Code Generator Widget using velo. Currently, all codes are running fine but the task reset scheduler in Wix backend (jobs.config) code is not working . Anyone know a solution for this?
Here is my code-

//Frontend Code
import wixData from 'wix-data';
import wixUsers from 'wix-users';

$w.onReady(function () {
    // Get the current user's ID
    const user = wixUsers.currentUser;
    const userId = user.id;

    // Query the UserTotalVisit collection for the current user
    wixData.query("UserTotalVisit")
        .eq("_id", userId)
        .find()
        .then(result => {
            if (result.items.length > 0) {
                let userDoc = result.items[0];

                // Check if the generatedNumbers field exists
                if (userDoc.generatedNumbers) {
                    // Set the repeater's data to the generatedNumbers array
                    $w("#repeater1").data = userDoc.generatedNumbers.map(code => ({ _id: code, code }));
                }
            }
        });

    $w("#generateButton").onClick(async () => {
        // Get the maximum length from the input
        const maxLength = 6;

        // Generate a random string of mixed numbers and alphabets
        const randomString = generateRandomString(maxLength);

        // Display the generated string in the text element
        $w("#resultText").text = randomString;

        // Query the UserTotalVisit collection for the current user
        let result = await wixData.query("UserTotalVisit")
            .eq("_id", userId)
            .find();

        // Check if the user document exists
        if (result.items.length > 0) {
            let userDoc = result.items[0];

            // Check if the generatedNumbers field exists, if not create it
            if (!userDoc.generatedNumbers) {
                userDoc.generatedNumbers = [];
            }

            // Add the new generated string to the array
            userDoc.generatedNumbers.push(randomString);

            // Update the user document in the collection
            await wixData.update("UserTotalVisit", userDoc);
        } else {
            // Create a new document for the user
            let newUserDoc = {
                _id: userId,
                generatedNumbers: [randomString]
            };

            // Insert the new document into the collection
            await wixData.insert("UserTotalVisit", newUserDoc);
        }

        // Refresh the repeater data
        $w("#repeater1").data = result.items[0].generatedNumbers.map(code => ({ _id: code, code }));
    });

    function generateRandomString(length) {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        const charactersLength = characters.length;
        for (let i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }

    // Function to set the repeater items
    $w("#repeater1").onItemReady(($item, itemData) => {
        $item("#codeText").text = itemData.code;
    });
});
//Backend Code to reset all attendance code (array field) as []
// In backend/clearGeneratedNumbers.js

import wixData from 'wix-data';

export async function clearGeneratedNumbers() {
    try {
        // Query all documents in the UserTotalVisit collection
        let result = await wixData.query("UserTotalVisit").find();

        // Loop through each document and clear the generatedNumbers array
        let updatePromises = result.items.map(async item => {
            item.generatedNumbers = [];
            return wixData.update("UserTotalVisit", item);
        });

        // Wait for all updates to complete
        await Promise.all(updatePromises);

        console.log("Generated numbers cleared successfully.");
    } catch (error) {
        console.error("Failed to clear generated numbers:", error.message);
    }
}
//job.config file code
// In backend/jobs.config

{
    "jobs": [
        {
            "functionLocation": "/clearGeneratedNumbers.js", 
            "functionName": "clearGeneratedNumbers",
            "description": "Clear the generatedNumbers array daily at 12 PM UTC",
            "executionConfig": {
                "time": "12:00"
            }
        }
    ]
}

Both Frontend and Backend Codes are Working But the jobs config is not auto resetting the array values

The issue with your jobs.config not resetting the generatedNumbers array might be due to a few reasons. Here’s how to troubleshoot:

1. Check Scheduled Task Logs:

  • Access your Wix dashboard and navigate to Automation > Scheduled Tasks .
  • Look for the “Clear the generatedNumbers array daily at 12 PM UTC” task.
  • Check the task logs for any errors that might be preventing successful execution.

2. Verify Function Call:

  • Inside the clearGeneratedNumbers.js function, ensure you’re calling wixData.update correctly. Double-check for typos or missing arguments.

3. Data Persistence Issue:

  • In rare cases, Wix Data might not immediately reflect changes made through scheduled tasks. Try adding a short delay (e.g., using setTimeout ) before querying the data again in your frontend code to allow for potential data refresh.

4. Consider Alternative Scheduling:

  • For testing purposes, try triggering the function manually from the Velo editor to verify it works independently of the scheduled task. This can help isolate the problem to the scheduling configuration.

Additional Tips:

  • Make sure the clearGeneratedNumbers.js file is located in the correct backend folder (backend ).
  • Double-check the time zone settings in your jobs.config . “12:00” might be interpreted differently depending on your Wix account settings. You can use a tool like Time Zone Converter – Time Difference Calculator to ensure it’s set for UTC.

If none of these solutions work, consider reaching out to Wix Support for further assistance. They can provide more in-depth analysis of your specific code and scheduled task configuration.

Fixed! Wrong “}” placement in at the end of the line. Thanks for the help!

1 Like