简体   繁体   中英

How can i do print string by time while i running http_serve_forever() in python

I am tring to run the httpserver on the raspberrypi to connect and send data via cellphone. I can send the data and run other function, but now I would like to print the string at 12 every day. I've tried sockettime and date_time_string

Here is my code:

from http.server import BaseHTTPRequestHandler, HTTPServer
import random
import os
from datetime import datetime, timedelta

class RequestHandler_httpd(BaseHTTPRequestHandler):
    def do_GET(self):
        global Request, test, data, case
        messagetosend = bytes('test', "utf")
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Content-Length', len(messagetosend))
        self.end_headers()
        self.wfile.write(messagetosend)
        Request = self.requestline
        Request = Request[5: int(len(Request)-9)]
        return
    def date_time_string(self, timestamp=None):


if __name__ == '__main__':
    server_address_httpd = ('192.168.66.19', 8080)
    httpd = HTTPServer(server_address_httpd, RequestHandler_httpd)
    print('start')
    httpd.serve_forever()

Any help would be appreciated.

I see five options:

1.) run your web server and add on the same machine a cronjob, that accesses the required url (for example with wget)

2.) run your web server and add a cronjob on another machine

3.) don't use a web server at all, but just use a cron job

4.) Depending on the framework you're using for the web server you might add a thread programming a timer, executing the job and reprogramming the timer.

In general However I try to avoid adding threads to a web server. You have to be careful to not do things, that are not thread safe and this can be tricky depending on your framework. but for some use cases it could be a simple solution.

5.) almost the same like for, but simulating an http request to your own url, which will probably avoid any race condition, which you might encounter with 4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM