简体   繁体   中英

Python Google Calendar API memory issue

I am using the reference Python code from Google (link below) which uses the Google Calendar API to get the next 10 events from my Gmail calendar. This is working fine.

However, my end goal is to have the calendar integrated for new events every 30 minutes. As such I have been running the code in a loop and I have noticed that each time the check is run the system memory used increases. Well I say every time but in fact it seems to be random. Sometimes it will run 50 times with no increase in footprint, other times it will increase every time. If run for long enough the app crashes.

I am running this on a Raspberry Pi if that is of any relevance. Sorry I confess to not being a developer, I really hope I am missing something obvious!

The code I am using came from here: https://developers.google.com/google-apps/calendar/quickstart/python#step_3_set_up_the_sample

The only changes I have made are to run the 'main' procedure in a loop as below:

while True:
    main()
    print ('Sleeping')
    sleep (60)

I have also inserted the following line of code to output the memory use at various points in the application:

print ('Memory usage at start: %s (kb)' % resource.getrusageresource.RUSAGE_SELF).ru_maxrss) #print memory usage

From the testing I have done it seems the memory use is increased by the service build:

service = discovery.build('calendar', 'v3', http=http)

I am looking for a way to stop the memory use getting out of hand, any help would be greatly appreciated.

Thank you in advance Tim

Try removing the lines below out of the loop by removing it from main() since this is just used for initializing your application's authentication.

credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)

Also, the parameter for sleep() is counted as seconds, use '1800' instead since you want it to run every 30 minutes.

You can try implementing your code like below

credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
while True:
main()
print ('Sleeping')
sleep (1800)

Also, you can wrap your service object with weakref.proxy object.

import weakref
# ... code
service = weakref.proxy(discovery.build('calendar', 'v3', http=http))

Works for me in multithreaded environment.

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