You can do pretty much anything you need to do with apex callouts [1] in batch apex [2]. Assuming you know how to access the Google Analytics reporting apis [3] then it should be pretty straight foward. However your question is pretty vague so unless you have a specific issue or additional questions, that's about the best I can do.
Thank you so much for your reply. I followed the instructions for using a service account, but kept getting 'invalid_grant' error. Do you have any suggestions what to check or do you have any work example I can take a look?
Oh, when I search on web for this error, some people said it could be caused by inaccurate system clock. But since I am running on salesforce platform, I have no control of that, and I would suppose the system clock on salesforce should be sync properly? So I should rule out this I suppose?
Invalid grant can be caused by several things. I can be because you are sending the wrong id, the wrong secret, the wrong token you are using the wrong grant_type. Is there any additional errors coming back? Have you tried using something like cURL or a REST tool to test that you can get the data back without involving Salesforce?
Thanks, pcon. Actually it does seem to be related to the system clock. Because the exact same code sometimes work, but most times does not. When I manually adjust the timestamp by -25 seconds, the chance of working get highest, but it is still very low (like only works 2 out of ten tries).
[1] https://developer.salesforce.com/page/Apex_Web_Services_and_Callouts
[2] https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm
[3] https://developers.google.com/analytics/devguides/reporting/
Oh, when I search on web for this error, some people said it could be caused by inaccurate system clock. But since I am running on salesforce platform, I have no control of that, and I would suppose the system clock on salesforce should be sync properly? So I should rule out this I suppose?
Long currTime = System.currentTimeMillis() / 1000
then use currTime for iat value.