Code is working in API calls But not working in Timer

Hi,
I wrote a code to check auction is ended or not and if auctions are ended the code will send a Push Notification to the host and also insert their entries in the Notification Table.
this code is running properly through API calls. but when I create Timer with the same code It is executed without error but does Nothing.

1 Like

Hello,
Any update on this ??

Hi @Ayaz_Khan ,

Sorry for the delay.
Could you please provide your app ID, name of the route for your custom logic and, if it is a timer written in Java, code of that timer?

Regards, Andriy

Hi @Andriy_Konoz,
Thanks for your reply Please Check Below
My App Id is : “C3B46A6B-6793-4561-9033-3845A19EC182”

Code is placed here: Backendless

Hello @Ayaz_Khan

Please provide a code sample for API Service (which works properly) and for the Timer (which doesn’t send PNs).

Do not share your entire code, just a minimum part (with one API for sending PNs) that can help us to reproduce the issue.

Regards, Vlad

Also, take a look at the following doc Sync vs Async Code - Developing Backendless Server Code with node.js

it might help you with debug your problem

Hello @vladimir-upirov ,
below is my code Please check,
this Code is working in API call but when I move it to timer it does not work.

    var date = new Date();
    var currentDateTime =
        ("00" + (date.getMonth() + 1)).slice(-2) + "/" +
        ("00" + date.getDate()).slice(-2) + "/" +
        date.getFullYear() + " " +
        ("00" + date.getHours()).slice(-2) + ":" +
        ("00" + date.getMinutes()).slice(-2) + ":" +
        ("00" + date.getSeconds()).slice(-2);
    let prevdate = new Date(date);
    prevdate.setHours(prevdate.getHours() - 1);
    var currentDate =
        ("00" + (prevdate.getMonth() + 1)).slice(-2) + "/" +
        ("00" + prevdate.getDate()).slice(-2) + "/" +
        prevdate.getFullYear();
    let cd = {
        'back': currentDate,
        'current': currentDateTime,
    }

    const queryBuilder = Backendless.DataQueryBuilder.create();
    queryBuilder.addProperties('ownerId', 'title', 'objectId').setWhereClause(`finished = false and (auction_end_date >= '${currentDate}' and auction_end_date <= '${currentDateTime}') `);
    let auction = Backendless.Data.of("Auctions").find(queryBuilder)
    var start_date = new Date();
    var status = true;
    let getAuctionId = [];
    let getOwnerId = [];
    let Bidders = [];
    if (auction.length > 0) {
        //auction.map(async function(data){ 
        auction.forEach(async function(data) {
            let auctionId = {
                'auctionId': data.objectId,
            }
            getAuctionId.push(auctionId)
            let ownerId = {
                'ownerId': data.ownerId,
                'title': data.title,
            }
            getOwnerId.push(ownerId)
            let info = {
                'actual_message': `Your auction, ${data.title} has ended. Choose the winner now!`,
                'notification_conditions_id': '7',
                'send_to': 'individual',
                'status': status,
                'ownerId': data.ownerId,

            }
            const uow = new Backendless.UnitOfWork();
            const notificationInsertResult = uow.create("Notification", info); //add the new notification to the table
            const userCouplingResult = uow.setRelation(notificationInsertResult, "auction_id", [data.objectId]);
            await uow.execute()


        });
        //}
     
      getOwnerId.map(async function(res) {
            const message = `Your auction, ${res.title} has ended. Choose the winner now!`;
            const queryBuilder = Backendless.DataQueryBuilder.create().setWhereClause(`user = '${res.ownerId}'`);
            await Backendless.Data.of("DeviceRegistration").find(queryBuilder)
                .then(async function(results) {
                    const channel = results[0].channelName;
                    const deviceId = results[0].deviceId;
                    const publishOptions = new Backendless.PublishOptions({
                            headers: {
                                "android-content-title": "Poze",
                                "ios-alert-title": "Poze",
                                "android-content-text": "Message",
                            }
                        }),

                        deliveryOptions = new Backendless.DeliveryOptions({
                            pushSinglecast: [deviceId] // devices IDs
                        });

                    return await Backendless.Messaging.publish(channel, message, publishOptions, deliveryOptions)
                        .then(function(messageStatus) {
                            return messageStatus;

                        })
                        .catch(function(error) {
                            return error;
                        });
                })
                .catch(function(error) {
                    return error;
                });
        })

        //await Promise.all(
        Promise.all(
            //auction.map(async function(data){
            auction.forEach(async function(data) {

                const bidsQueryBuilder = Backendless.DataQueryBuilder.create();
                bidsQueryBuilder.setWhereClause(`Auction_objectId = '${data.objectId}'`);
                bidsQueryBuilder.addProperties('Bidder_objectId').setSortBy(["bid_amount DESC"]);
                bidsQueryBuilder.setPageSize(5);
                let TopBidders = await Backendless.Data.of("TopBidders").find(bidsQueryBuilder)
                await Promise.all(
                    TopBidders.map(async function(res) {
                        const queryBuilder = Backendless.DataQueryBuilder.create();
                        queryBuilder.setWhereClause(`user_objectId = '${res.Bidder_objectId}' and auction_objectId = '${data.objectId}'`);
                        let whybid = await Backendless.Data.of("WhyBidding").find(queryBuilder);
                        await Promise.all(
                            whybid.map(async function(result) {
                                if (whybid != null && whybid != undefined) {
                                    const queryBuilder2 = Backendless.DataQueryBuilder.create().setWhereClause(`(receiver = '${result.user_objectId}' and sender = '${data.ownerId}') or (receiver = '${data.ownerId}' and sender = '${result.user_objectId}')`);
                                    let savedObject = await Backendless.Data.of("Messages").find(queryBuilder2)
                                    if (savedObject.length === 0) {
                                        const newRoomId = `${result.user_objectId}-${data.ownerId}`;
                                        let insertData = {
                                            text: `What motivated me to bid on ${data.title} is ${result.bid_text}`,
                                            roomId: newRoomId,
                                            lastMessage: 1,
                                        }
                                        const uow = new Backendless.UnitOfWork();
                                        const InsertResult = uow.create("Messages", insertData);
                                        const insertReceiverObjectId = uow.addToRelation(InsertResult, "receiver", [data.ownerId]);
                                        const insertSenderObjectId = uow.addToRelation(InsertResult, "sender", [result.user_objectId]);
                                        await uow.execute()


                                        let getbidder = {
                                            'aution_id': data.objectId,
                                            'ownerId': data.ownerId,
                                            'auction_title': data.title,
                                            'topbidder': TopBidders,
                                            'whybidmessage': result,
                                            'insertmessage': insertSenderObjectId,
                                        }

                                        Bidders.push(getbidder)
                                    } else {
                                        let insertData = {
                                            text: `What motivated me to bid on ${data.title} is ${result.bid_text}`,
                                            roomId: savedObject[0].roomId,
                                            lastMessage: 1,
                                        }
                                        let updateLastMessage = {
                                            'lastMessage': 0,
                                        }

                                        await Backendless.Data.of("Messages").bulkUpdate(`roomId = '${insertData.roomId}'`, updateLastMessage)
                                        const uow = new Backendless.UnitOfWork();
                                        const InsertResult = uow.create("Messages", insertData);
                                        const insertReceiverObjectId = uow.addToRelation(InsertResult, "receiver", [data.ownerId]);
                                        const insertSenderObjectId = uow.addToRelation(InsertResult, "sender", [result.user_objectId]);
                                        await uow.execute()
                                        let getbidder = {
                                            'aution_id': data.objectId,
                                            'ownerId': data.ownerId,
                                            'auction_title': data.title,
                                            'topbidder': TopBidders,
                                            'whybidmessage': result,
                                            'insertmessage': insertData
                                        }

                                        Bidders.push(getbidder)
                                        const message = `What motivated me to bid on ${data.title} is ${result.bid_text}`;
                                        const queryBuilder = Backendless.DataQueryBuilder.create().setWhereClause(`user = '${data.ownerId}'`);
                                        await Backendless.Data.of("DeviceRegistration").find(queryBuilder)
                                            .then(async function(results) {
                                                const channel = results[0].channelName;
                                                const deviceId = results[0].deviceId;
                                                const publishOptions = new Backendless.PublishOptions({
                                                        headers: {
                                                            "android-content-title": "Poze",
                                                            "ios-alert-title": "Poze",
                                                            "android-content-text": "Message",
                                                        }
                                                    }),

                                                    deliveryOptions = new Backendless.DeliveryOptions({
                                                        pushSinglecast: [deviceId] // devices IDs
                                                    });

                                                return await Backendless.Messaging.publish(channel, message, publishOptions, deliveryOptions)
                                                    .then(function(messageStatus) {
                                                        return messageStatus;

                                                    })
                                                    .catch(function(error) {
                                                        return error;
                                                    });
                                            })
                                            .catch(function(error) {
                                                return error;
                                            });

                                    }
                                }
                            }));

                    })
                );

            })
        );
    }
    return auction;

Hello @Ayaz_Khan!

Where can I find and test an api call with working business logic?

You can also split your code into parts and try to test them separately to see where you have the problem.

Regards,
Alexander

Hello @Alexander_Pavelko,

API URL is-
https://api.backendless.com/C3B46A6B-6793-4561-9033-3845A19EC182/xxx/services/IshraqueService/auctionEnd
It is working in API but not working in timer.
also, we try this
“You can also split your code into parts and try to test them separately to see where you have the problem.”
but found Nothing

please provide a minimal code sample, according to our support policy we do not debug customers’ code.

Regards, Vlad

Hi @vladimir-upirov,

Here is my code sample to send PN to users from CronJob (Timer), it is working in API code but not in Timer

   const queryBuilder = Backendless.DataQueryBuilder.create().setWhereClause(`user = '${data.ownerId}'`);
                await Backendless.Data.of("DeviceRegistration").find(queryBuilder)
                .then(async function( results ) {
                  const channel = results[0].channelName;
                  const deviceId = results[0].deviceId;
              const publishOptions = new Backendless.PublishOptions({
               headers: {
                   "android-content-title": "Poze",
                   "ios-alert-title":"Poze",
                   "android-content-text":"Message",
                  }
                }),
                
                deliveryOptions = new Backendless.DeliveryOptions({
                  pushSinglecast: [deviceId] // devices IDs
                });
        
               return await Backendless.Messaging.publish( channel, message, publishOptions, deliveryOptions )
                .then( function( messageStatus ) {
                return messageStatus;
                  
                })
                .catch( function( error ) {
                  return error;
                });
              })

thanks @Ayaz_Khan

Actually, I do not see any issue with this code, try to add a couple of console.log in order to see intermediate results