[Django]-TypeError: the first argument must be callable when I import a scheduler in my views.py file of django?

2👍

Fixing the scheduling call

By writing:

schedule.every().day.at("17:19").do(republic(requests))
schedule.every().day.at("17:19").do(republic(requests))
schedule.every().day.at("17:19").do(republic(requests))

You schedule the result of the republic(request) as job, not “calling republic with requests as job“.

The do(job_func, *args, **kwargs) [schedule-doc] function however allows to provide parameters, you provide these after a reference to the job, so:

schedule.every().day.at("17:19").do(republic, requests)
schedule.every().day.at("17:19").do(republic, requests)
schedule.every().day.at("17:19").do(republic, requests)

Running the scheduler in a specific thread

You can not run the scheduler this way in Django, since it will mean that you keep running the command when loading the file. So loading the file will never terminate, and hence the server will never start.

You can run the scheduler asynchronous however, with:

from threading import Thread
from __future__ import print_function
from django.shortcuts import render
from django.utils import timezone
from django.http import HttpResponse
from datetime import datetime, timedelta
import requests
import schedule
import time


def republic(request):
    return HttpResponse("<h1>Success Hindustan</h1>")

schedule.every().day.at("17:19").do(republic, requests)
schedule.every().day.at("17:19").do(republic, requests)
schedule.every().day.at("17:19").do(republic, requests)

class SchedulerThread(Thread):
     @classmethod
     def run(cls):
         while True:
             schedule.run_pending()
             time.sleep(interval)

ScheduleThread().start()

Finally note that requests is not a HttpRequest object, so you should not write your functions as views, but as “vanilla” functions that perform certain work.

5👍

republic(requests) will return HttpResponse,

so the execution would be

schedule.every().day.at("17:19").do(HttpResponse)

inside do method you should mention function, not class instance.
you can use one of the below

solution 1:

schedule.every().day.at("17:19").do(lambda: republic(requests))

solution 2.

schedule.every().day.at("17:19").do(republic, requests)

solution 3.

import functools
schedule.every().day.at("17:19").do(functools.partial(republic, requests))

2👍

based on the schedule.Job.do, you should pass args after the function:

schedule.every().day.at("17:19").do(republic, requests)
schedule.every().day.at("17:19").do(indiatv, requests)
schedule.every().day.at("17:19").do(ndtv, requests)

do(job_func, *args, **kwargs)

Specifies the job_func that should be called every time the job runs.
Any additional arguments are passed on to job_func when the job runs.

Leave a comment