How to Schedule Fetch URL using Cron Triggers

How can i make this thing work. what i am doing wrong?

addEventListener('scheduled', event => {
  event.waitUntil(
    handleSchedule(event.request)
  )
})

async function handleSchedule(request) {
    console.log(scheduledDate)
    const { pathname } = new URL(request.url);
    let stampDate = Date.now();
    let localDate = new Date (stampDate);
    let obj
    const LOG_URL = "https://api.telegram.org/xxx:xxx-dAv4EKac/editMessageText?chat_id=-xxx&message_id=49&[email protected]%20Status\n\n"
    const fetch_status = await fetch("https://xxx.telegram.ind.in", {
            method: "GET",
            })
    if (fetch_status.ok) {
        var statustext = await fetch_status.text()
        obj = await JSON.parse(statustext);
        return await fetch(LOG_URL+"Status: "+obj.server_status+"\nUptime: "+obj.uptime+"\nLoad: "+obj.loads.bot1+"\n\nLast Checked: "+localDate, {
            method: "GET",
        })
    } else {
        var statustext = "Server Offline"
        return await fetch(LOG_URL+"Status: "+statustext+"\n\nLast Checked: "+localDate, {
            method: "GET",
        })
    }   
}

There is no request property for a scheduled event. You can not return a response either. docs for ScheduledEvent.

Can we ping a url using Cron trigger every minute? Any code for that?

Probably something like this. Haven’t tested this code

addEventListener('scheduled', event => {
  event.waitUntil(
    handleSchedule(event)
  )
})

async function handleSchedule(event) {
    console.log(event.scheduledTime)
    const { pathname } = "< YOUR URL HERE>;
    let stampDate = Date.now();
    let localDate = new Date (stampDate);
    let obj
    const LOG_URL = "https://api.telegram.org/xxx:xxx-dAv4EKac/editMessageText?chat_id=-xxx&message_id=49&[email protected]%20Status\n\n"
    const fetch_status = await fetch("https://xxx.telegram.ind.in", {
            method: "GET",
            })
    if (fetch_status.ok) {
        var statustext = await fetch_status.text()
        obj = await JSON.parse(statustext);
        await fetch(LOG_URL+"Status: "+obj.server_status+"\nUptime: "+obj.uptime+"\nLoad: "+obj.loads.bot1+"\n\nLast Checked: "+localDate, {
            method: "GET",
        })
    } else {
        var statustext = "Server Offline"
        await fetch(LOG_URL+"Status: "+statustext+"\n\nLast Checked: "+localDate, {
            method: "GET",
        })
    }   
}
2 Likes

Thanks, It worked, just had to remove some undefined lines.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.